Simple-II. Rotate string to the left

The left rotation operation of the string is to transfer several characters in front of the string to the end of the string. Please define a function to realize the left rotation operation of the string. For example, if you enter the string "abcdefg" and the number 2, the function will return the result "cdefgab", which is rotated two bits to the left.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Example 1:

Input: s = "abcdefg", k = 2
Output: "cdefgab"

The following is the time complexity of my Caiji solution is O(n^2)

public static String reverse(String s, int n) {
    
    

        char[] chars = s.toCharArray();
        int index=0;
        int count = 0;
        char temp;
        while (count < n) {
    
    
            temp =chars[0];
            while(true){
    
    
                chars[index]=chars[index+1];
                if(++index == chars.length-1){
    
    
                    count++;
                    break;
                }
            }
            chars[chars.length-1]=temp;
            index=0;
        }
        s = String.valueOf(chars);
        return s;
    }
public static String improveReverse(String s, int n ){
    
    

        return s.substring(n,s.length())+s.substring(0,n);
    }
public static String improveReverse2(String s, int n ){
    
    
        String res ="";
        char[] chars = s.toCharArray();
        for (int i = n; i < chars.length; i++) {
    
    
             res+=chars[i];
        }
        int index=0;
        while(index<n){
    
    
            res +=chars[index++];
        }
        return res;
    }

Guess you like

Origin blog.csdn.net/qq_41729287/article/details/112347225