字符旋转问题-Rotate the string

本文通过一个字符串旋转的问题,探讨了高效解决此类问题的方法。从最初的直接循环实现到利用C++标准库函数优化,最终实现了时间和空间效率更高的解决方案。

Problem 4:

Given a string and an offset, rotate string by offset. (rotate from left to right)

Example

Given "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
解析:第一次我按字符考虑,想要走for循环,果真Time Error,一个case都没跑过:

class Solution {
public:
    /*
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here
    while(offset>0){
        int x = str.length();
        char m = str.at(x-1);
        for(int i = x-1 ; i>0;i--){
            str[i] = str[i-1];
        }
        str[0] = m;
    }
    
    }
};

然后我就去翻c++ string库的函数了... 再观察case规律发现,只是相对位置发生了变化,本质上是将原字符串根据offset拆分成前后两片,再调换位置的过程,所以写了下面的代码:

class Solution {
public:
    /*
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here
        int x = str.length();
      string sub_1 = str.substr(x-offset,offset);
      string sub_2 = str.substr(0,x-offset);
      sub_1 += sub_2;
      str = sub_1;
    }
};
结果跑到一半就跪了,看到case是这样的:


嗯...果然自己想得不周到,加上了

offset = offset%x;进行处理,后来又在一个空字符串上坑了一把,最后AC的代码如下:

class Solution {
public:
    /*
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here
    
        int x = str.length();
        if(x > 0){
        offset = offset%x;
        string sub_1 = str.substr(x-offset,offset);
        string sub_2 = str.substr(0,x-offset);
        sub_1 += sub_2;
        str = sub_1;
        }
    }
};
感悟:多看函数库,把程序方方面面想到,尽量一把AC,摒弃for循环。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值