⚡️Algorithm Exercise~String - Left Rotate String~⚡️

describe

There is a shift instruction in assembly language called Rotate Left (ROL). Now there is a simple task to simulate the operation result of this instruction with a string. For a given character sequence S, please rotate it to the left by K bits to output the sequence (guarantee that K is less than or equal to the length of S). For example, the character sequence S=”abcXYZdef” requires to output the result of 3-bit circular left shift, namely “XYZdefabc”. Is not it simple? OK, get it done!

example

Input: "abcXYZdef",3

Return value: "XYZdefabc"

answer

There is a method that is not the optimal solution, but it is relatively simple, string inversion

public class Solution {
    
    
    public String LeftRotateString(String str,int n) {
    
    
        if(n > str.length()){
    
    
            return "";
        }
        String substring = str.substring(0, n);
        String substring1 = str.substring(n);
        return substring1+substring;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43863054/article/details/120436410