"Left Rotation String" of "Swords Offer"

Topic description


There is a shift instruction in assembly language called Rotate Left (ROL), and now there is a simple task to simulate the operation result of this instruction with a string. For a given character sequence S, please output the sequence after it is cyclically shifted to the left by K bits. For example, the character sequence S=”abcXYZdef” requires the output of the result of cyclic left shift by 3 bits, that is, “XYZdefabc”. Is not it simple? OK, get it done!

Code



//按照剑指offer书上的方法,三次翻转字符串。
class Solution {
public:
    string LeftRotateString(string str, int n) {
        reverse(str.begin(), str.end());
        reverse(str.begin(), str.begin() + str.size() - n);
        reverse(str.begin() + str.size() - n, str.end());
        return str;
    }
};
//比较好想,但时间复杂度高。
class Solution {
public:
    string LeftRotateString(string str, int n) {
        if( n > str.length()){
            return "" ;
        }
        string a = str.substr(0,n);
        string b = str.substr(n,str.length());
        return b+a;

    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325609417&siteId=291194637