[String] Rotate string to the left

Title description

There is a shift instruction in assembly language called Rotate Left (ROL). Now there is a simple task, which is to simulate the operation result of this instruction with a string. For a given character sequence S, please output the sequence after circularly shifting it K bits to the left. For example, the character sequence S="abcXYZdef", it is required to output the result of the circular shift left by 3 bits, that is, "XYZdefabc". Is not it simple? OK, get it done!
Example 1
input
"abcXYZdef", 3

Return value
"XYZdefabc"


This question is less difficult. You can use string interception to splice two parts of the string together. For example, if abcXYZdef is shifted to the left by 3 digits, then XYZdef and abc can be put together. Note that when the number of left shifts is equal to the length of the string It is equivalent to no movement, so first take the remainder of the string length of n and then concatenate

public class Solution {
    
    
    public String LeftRotateString(String str, int n) {
    
    
        /*
        "abcXYZdef",3
        返回值
        "XYZdefabc"
        */
        if (str.length() == 0)
            return str;
        n %= str.length();
        return str.substring(n) + str.substring(0, n);
    }
}

Guess you like

Origin blog.csdn.net/weixin_43486780/article/details/113810234