代码随想录算法训练营DAY7|344.反转字符串,541. 反转字符串II,剑指Offer 05.替换空格,151.翻转字符串里的单词,剑指Offer58-II.左旋转字符串

344.反转字符串

题目链接:

https://leetcode.cn/problems/reverse-string/

解题方法

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

题目链接:

https://leetcode.cn/problems/reverse-string-ii/

解题方法:

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;
    }
};

剑指Offer 05.替换空格

题目链接:

https://leetcode.cn/problems/ti-huan-kong-ge-lcof/

解题方法:

class Solution {
public:
    string replaceSpace(string s) {

        int count = 0;
        int oldSize = s.size();
        int newSize = 0;
        for(int i = 0; i< s.size();i++)
        {
            if(s[i] == ' ')
            {
                count ++;
            }
        }

        s.resize(s.size() + 2 * count);
        newSize = s.size();
        for(int i = newSize - 1, j = oldSize - 1; j < i; j--,i--)
        {
              if(s[j] != ' ')
              {
                  s[i] = s[j];
              } 
              else
              {
                  s[i] = '0';
                  s[i - 1] = '2';
                  s[i - 2] = '%';
                  i -= 2;  
              } 
        }
        return s;
    }
};

151.翻转字符串里的单词

题目链接:

https://leetcode.cn/problems/reverse-words-in-a-string/

剑指Offer58-II.左旋转字符串

题目链接:

https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/

解题方法:

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        reverse(s.begin(), s.begin() + n);
        reverse(s.begin() + n, s.end());
        reverse(s.begin(), s.end());
        return s;
    }
};

你可能感兴趣的:(代码随想录算法训练营第九期,leetcode)