面试题42:左旋转字符串(未)

题目描述
对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。

题目分析

暴力解法:一次移动一位

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if (n == 0 || n == str.size())
            return str;
        while (n > 0) {
            LeftOneRotate(str);
            -- n;
        }
        return str;
    }
    void LeftOneRotate(string &str) {
        char temp = str[0];
        for (int i = 1; i < str.size(); i ++)
            str[i - 1] = str[i];
        str[str.size() - 1] = temp;
    }
};

猜你喜欢

转载自blog.csdn.net/zxc995293774/article/details/80302775
今日推荐