Leetcode-Left Roate the String

superorange 2022/07/11 381Views

Left Roate the String

leetcode: https://leetcode.cn/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof

Description:

The left rotation operation of a string is to transfer several characters in front of the string to the end of the string. Please define a function to implement the function of left rotation of strings. For example, input the string “abcdefg” and the number 2, the function will return the result “cdefgab” obtained by left-rotating two places.

Idea:

Solution1:

Step1: create new string, and split the original string according to the number, then combine them

this solution will cost more Space complexity

Code:

class Solution {
    public String reverseLeftWords(String s, int n) {
        String string1 ="";
        for(int i =n; i<s.length(); i++){
            string1 = string1 + s.charAt(i);
        }
        for(int i=0; i<n; i++){
            string1 += s.charAt(i);
        }
        return string1;
    }
}

Solution2:

Step1: Reverse the substring before the specific number

Step2: Reverse the substring after the number

Step3: Reverse the whole string

Code:

class Solution {
    public String reverseLeftWords(String s, int n) {
        char[] result = s.toCharArray();
        reverse(result,0,n-1);
        reverse(result,n,s.length()-1);
        reverse(result,0,s.length()-1);
        return new String(result);
    }
    public void reverse(char[]s, int i, int j){
        while(i<j){
            char temp = s[i];
            s[i] = s[j];
            s[j] = temp;
            i++;
            j--;
        }
    }
}