43. Rotate String Left

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!

Problem solving ideas

          The following method is tricky and should be solved by string flipping;

    public String LeftRotateString(String str,int n) {
        int length = str.length();
        if (length == 0){
            return "";
        }
        
        n = n%length;

        String result = str+str;
        return result.substring(n,n+length);
    }

Guess you like

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