代码随想录训练营第8天| 344.反转字符串 541. 反转字符串II 151.翻转字符串里的单词

344.反转字符串

题目:Leetcode 

文档:代码随想录

视频:B站视频

class Solution {
public:
    void reverseString(vector& s) {
        for (int i = 0, j = s.size() - 1; i < s.size()/2; i++, j--)
            swap(s[i],s[j]);
    }
};

541. 反转字符串II


 题目:Leetcode

文档:代码随想录

视频:B站视频 

 遍历字符串的过程让 i += (2*k),i 每次移动2*k 就可以了,然后判断是否需要有反转的区间

class Solution {
public:
    string reverseStr(string s, int k) {
    for (int i = 0; i < s.size(); i += (2 * k))
    {
        if (i + k <= s.size()) 
            reverse(s.begin() + i, s.begin() + i + k );
        else 
            reverse(s.begin() + i, s.end());
    }
    return s;
    }
};

151.翻转字符串里的单词


题目:Leetcode

文档:代码随想录

视频:B站视频 

class Solution {
public:
    void reverse(string& s, int l, int r)
    {
        for (int i = l, j = r; i < j; i++, j--)
            swap(s[i], s[j]);
    }

    void removeExtraSpaces(string& s) 
    {
        int slow = 0;
        for (int i = 0; i < s.size(); ++i) 
        {
            if (s[i] != ' ')
            { 
                if (slow != 0) s[slow++] = ' '; 
                while (i < s.size() && s[i] != ' ') 
                {
                    s[slow++] = s[i++];
                }
            }
        }
        s.resize(slow);
    }

    string reverseWords(string s) {
        removeExtraSpaces(s);
        reverse(s, 0, s.size()-1);
        int start =0;
        for(int i =0; i <= s.size(); ++i)
        {
            if (i == s.size() || s[i] == ' ') 
            {
                reverse(s, start, i - 1);
                start = i + 1;
            }
        }
        return s;
    }
};

你可能感兴趣的:(算法,leetcode,数据结构)