首页 > 其他分享 >代码随想录day8 LeetCode 344 反转字符串 541反转字符串II 剑指 Offer 05. 替换空格 151.翻转字符串里的单词 剑指 Offer 58 - II. 左旋转字符串

代码随想录day8 LeetCode 344 反转字符串 541反转字符串II 剑指 Offer 05. 替换空格 151.翻转字符串里的单词 剑指 Offer 58 - II. 左旋转字符串

时间:2023-01-05 15:35:54浏览次数:71  
标签:cn Offer int II 字符串 string

344 反转字符串

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

双指针

class Solution {
public:
    void reverseString(vector<char>& s) {
       int left=0;int right=s.size()-1;
       char temp;
       while(left<right){
           temp=s[left];
           s[left]=s[right];
           s[right]=temp;
           left++;
           right--; 
       }
    }
};

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);
                continue;
            }
              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 presize=s.size();
        for(int i=0;i<s.size();i++){
            if(s[i]==' ')count++;
        }
        s.resize(s.size()+count*2);
       int nowsize=s.size();
//从后往前替换 for(int i=nowsize-1,j=presize-1;j<i;i--,j--){ 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/submissions/

class Solution {
public:
    void reverse(string& s, int start, int end){ //翻转,区间写法:左闭又闭 []
        for (int i = start, j = end; i < j; i++, j--) {
            swap(s[i], s[j]);
        }
    }
    string reverseWords(string s) {
        int slow=0;
        for(int fast=0;fast<s.size();fast++){
           if(s[fast]!=' ') {
               if (slow != 0)s[slow++] = ' ';
               while (fast < s.size() && s[fast] != ' ') {
                   s[slow] = s[fast];
                   slow++;
                   fast++;
               }
           }
        }
        s.resize(slow);
        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;
    }
};

剑指 Offer 58 - II. 左旋转字符串

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

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        while(n--){
            int temp=s[0];
            for(int i=1;i<s.size();i++){
                s[i-1]=s[i];
            }
            s[s.size()-1]=temp;
        }
        return s;
    }
};

 

标签:cn,Offer,int,II,字符串,string
From: https://www.cnblogs.com/zhishikele/p/17027712.html

相关文章