跳至主要內容

4. 字符串

pptg大约 1 分钟

LeetCode.344.反转字符串open in new window

// 左右对称交换
class Solution {
public:
    void reverseString(vector<char>& s) {
        int l = 0;
        int r = s.size()-1;
        while(l < r){
            int t = s[l];
            s[l] = s[r];
            s[r] = t;
            l++;
            r--;
        }
    }
};

LeetCode.541.反转字符串IIopen in new window

// 官方题解又允许用reverse了?
class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.size();
        int max_k_cnt = n/2/k;
        int last = n - max_k_cnt*2*k;
        for(int i = 0;i < max_k_cnt;i++){
            int l = 2*k*i;
            int r = 2*k*i+k-1;
            while(l < r){
                char t = s[l];
                s[l] = s[r];
                s[r] = t;
                l++;
                r--;
            }
        }
        if(last < k){
            int l = 2*k*max_k_cnt;
            int r = n-1;
            while(l < r){
                char t = s[l];
                s[l] = s[r];
                s[r] = t;
                l++;
                r--;
            }
        }
        if(last >= k && last < 2*k){
            int l = 2*k*max_k_cnt;
            int r = 2*k*max_k_cnt+k-1;
            while(l < r){
                char t = s[l];
                s[l] = s[r];
                s[r] = t;
                l++;
                r--;
            }
        }
        return s;
    }
};

class Solution {
public:
    string reverseStr(string s, int k) {
        int n = s.length();
        for (int i = 0; i < n; i += 2 * k) {
            reverse(s.begin() + i, s.begin() + min(i + k, n));
        }
        return s;
    }
};

LeetCode.151.反转字符串中的单词open in new window

// 从后向前判断
// 双flag取字符串
class Solution {
public:
    string reverseWords(string s) {
        bool fEd = false;
        int ed = 0, st = 0;
        string anss;
        for(int i = s.size()-1;i >= 0;i--){
            if(s[i] != ' '){
                if(!fEd) {
                    ed = i; 
                    fEd = !fEd;
                }
                st = i;
            }
            if(s[i] == ' ' || i == 0){
                if(fEd){
                    anss += s.substr(st,ed-st+1) + ' ';
                    fEd = !fEd;
                }
            }
        }
        return anss.substr(0,0+anss.size()-1);
    }
};