43. 左旋转字符串

题目描述:汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!

方法一:

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str.size() == 0)
            return "";
        string str1 = ""; 
        int len = str.size();
        n = n%len;
        for(int i = n; i < len; ++ i) 
            str1 += str[i];
        for(int i = 0; i < n; ++ i)
            str1 += str[i];
        return str1;
    }
};

方法二:

利用substr函数:substr(index, len)返回一个从指定位置开始,并具有指定长度的字符串。

class Solution {
public:
    string LeftRotateString(string str, int n) {
        int len = str.size();
        if(len == 0)
            return "";
        n = n%len;
        str += str;
        return str.substr(n, len);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_39605679/article/details/81394973