語順の逆-1

リコウ住所

従来の慣行:

1つずつトラバースしてからスプライスします

class Solution {
public:
    string reverseWords(string s) {
        string res, tmp;
        for (auto c : s) {
            if (c != ' ') {
                tmp += c;
                continue;
            }
            if (tmp.size()) {
                res = tmp + " " + res;
                tmp.clear();
            }
        }
        if (tmp.size()) {
            res = tmp + " " + res;
            tmp.clear();
        }
        return res.substr(0, res.size() - 1);
    }
};

ダブルポインタ:

上記の方法では、文字が1つずつスプライスされるため、効率が低下します。実際、文字列の最初の位置を選択して、一度にスプライスすることができます。

class Solution {
public:
    string reverseWords(string s) {
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        if (!s.size()) return s;
        int i = s.size() - 1;
        int j = i;
        string res;
        while (i >= 0) {
            while (i >= 0 && s[i] != ' ') --i;
            res += s.substr(i + 1, j - i) + ' ';
            while (i >= 0 && s[i] == ' ') --i;
            j = i;
        }
        return res.substr(0, res.size() - 1);
    }
};

 

おすすめ

転載: blog.csdn.net/TESE_yan/article/details/114418738