[] To prove safety Offer- knowledge of migration face questions 58.2: string left rotation

Title Description

There is a shift in the assembly language instruction called a rotate left (the ROL), and now there is a simple task, this instruction is simulated by the string operation result. For a given character sequence S, you put its left circle after K-bit serial output. For example, the character sequence S = "abcXYZdef", rotated left required output result after three, i.e. "XYZdefabc". Is not it simple? OK, get it!
Note: This question is face questions 58: Flip word order expansion.

Ideas 1

Left rotation is actually the string into two parts, and then reverse the order of two parts. If the string when the character string type, it can be done directly substr. code show as below:

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str=="")
            return "";
        
        string part1 = str.substr(0, n);
        string part2 = str.substr(n, str.length()-n);
        return part2+part1;
    }
};

Ideas 2

1 idea is not the intention of this question (although personally feel that the idea of a simpler method code). This problem is face questions 58: inverted word order extending, it can be done in a similar way. Suppose we want to flip the order of words in a sentence, such as "hello world", is inverted to "world hello", which is equivalent to hello moved behind the world (not exactly the same, because there are spaces, but the idea is similar). For this problem, we can put a string into two parts, such as the "abcXYZdef" before the three "abc" into the back, which is divided into "abc" "XYZdef" in two parts, let's flip the two parts separately, to give "cba" "fedZYX", then flip the entire string, to give "XYZdefabc". So the process is:
(1) The position of the character string divided into two parts;
(2) flipping two parts, respectively;
(3) the two parts as a whole flip.
code show as below:

class Solution {
public:
    string LeftRotateString(string str, int n) {
        if(str=="")
            return "";
        
        string part1 = str.substr(0, n);
        string part2 = str.substr(n, str.length()-n);
        part1 = reverse(part1);
        part2 = reverse(part2);
        str = part1+part2;
        return reverse(str);
    }
    
    string reverse(string str){
        int left = 0;
        int right = str.length()-1;
        while(left<right){
            swap(str[left], str[right]);
            left++;
            right--;
        }
        return str;
    }
};

If the string is a string type, this method is really simple question complicated. This method is suitable for the case of using a character string represented by the array.

Guess you like

Origin www.cnblogs.com/flix/p/12530179.html