AcWing 77. 翻轉單詞順序

習題地址 https://www.acwing.com/problem/content/description/73/算法

題目描述
輸入一個英文句子,翻轉句子中單詞的順序,但單詞內字符的順序不變。spa

爲簡單起見,標點符號和普通字母同樣處理。指針

例如輸入字符串」I am a student.」,則輸出」student. a am I」。code

樣例blog

輸入:"I am a student."

輸出:"student. a am I"

 

算法1
除開先翻轉整個句子 再反轉單詞的作法 個人比較硬核 直接逐個雙指針的翻轉整個單詞ip

 

代碼字符串

class Solution {
public:
int findsubString(const string& s, string& revertStr ,size_t& findPos) {
    size_t start = s.find_last_not_of(' ', findPos);
    if (start == string::npos) {
        return -1;
    }
    findPos = start ;
    size_t end = s.find_last_of(' ', findPos);

    findPos = end; int len = 0;
    if (end == string::npos){
        end = 0;
        len = start - end + 1;
    }
    else{
        end++;
        len = start - end+1;
    }
    revertStr += s.substr(end, len);
    if (findPos == string::npos)
        return -1;
    revertStr += " ";

    return 1;
}


string reverseWords(string s) {
    if (s.empty()) return s;
    string res;
    size_t findPos = s.size()-1;
    int ret = findsubString(s, res, findPos);

    while (ret == 1) {
        ret = findsubString(s, res, findPos);
    }

    return res;
}

};

做者:defddr
連接:https://www.acwing.com/solution/acwing/content/2907/
來源:AcWing
著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
相關文章
相關標籤/搜索