[Offer] [58-2] [String] left rotation

Title Description

  Left rotational operation in front of the string is the string of several characters to the end of the string transfer. Define a function to achieve a left rotation operation function string. For example, the input string "abcdefg" and the number 2, this function returns two results obtained left rotation "cdefgab".

Cattle brush off questions address network

Ideas analysis

  The first incoming n string divided into two parts, the two parts are turned over, and then reversing the string in the overall
 

Test Case

  1. Functional test: the string of length n characters left rotation 0, 1 character, 2 characters, n-1 characters, characters n, n + 1 characters.
  2. Special Test Input: string pointer is nullptr pointer.

Java code

public class Offer058_02 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

    public static String LeftRotateString(String str, int n) {
        return Solution1(str, n);
    }

    private static String Solution1(String str, int n) {
        
        if(str==null|| str.length()<=0) {
            return str;
        }
        if(n<=0 || n> str.length()) {
            return str;
        }
        char[] charArray = str.toCharArray();
        
        reverseCore(charArray, 0, n-1);
        reverseCore(charArray, n, charArray.length-1);
        reverseCore(charArray, 0, charArray.length-1);
        return String.valueOf(charArray);
    }
    
    private static void reverseCore(char[] s,int start,int end) {
        while(start<end) {
            char tmp = s[start];
            s[start] = s[end];
            s[end] = tmp;
            start++;
            end--;
        }
    }

    private static void test1() {

    }

    private static void test2() {

    }

    private static void test3() {

    }

}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer582-zuo-xuan-zhuan-zi-fu-chuan.html