剑指Offer-第3天 字符串(简单)

第一题

题目链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

个人题解:遍历,当碰到空格,抹去空格,插入字符串。

代码:

class Solution {
public:
    string replaceSpace(string s) {
        for(int i=0;i<s.size();i++){
            if(s[i]==' '){
                s.erase(s.begin()+i, s.begin()+i+1);
                s.insert(i, "%20");
            }
        }
        return s;
    }
};

结果:

image

第二题

题目链接:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/

个人题解:旋转前 \(n\) 项,旋转后 \(n\) 项,旋转全部即可得到答案。

代码:时间复杂度 \(O(n)\),空间复杂度 \(O(1)\);

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

结果:

image

posted @ 2022-05-05 11:09  黑VS白-清墨  阅读(30)  评论(0)    收藏  举报