Arrow refers to left rotation strings offer

Title Description

There is a shift in the assembly language instruction called a rotate left (the ROL), and now there is a simple task, this instruction is simulated by the string operation result. For a given character sequence S, you put its left circle after K-bit serial output. For example, the character sequence S = "abcXYZdef", rotated left required output result after three, i.e. "XYZdefabc". Is not it simple? OK, get it!
1 ideas: the use of subString String class () method withdrawn substring
String substring(int beginIndex, int endIndex)
It returns a string that is a child of this string. 
   String class using the API concat () implement string concatenation
String concat(String str)
The specified string is connected to the end of the string.
Code:
public class Solution {
    public String LeftRotateString(String str,int n) {
        if (str == null || str.length() == 0 || n < 0 || n > str.length()) {
            return str;
        }
        n %= str.length();
        String str1 = str.substring(0,n);
        String str2 = str.substring(n,str.length());
        return str2.concat(str1);
    }
}

  2 ideas:

* 1. First half of the front reversing
* 2. The latter half is reversed again
* 3. And then the entire string flip
*
* test sites: the string does not use flexible database flipped

public class Solution {
    public String LeftRotateString(String str,int n) {
        if(str == null || str.length()==0 || n < 0 || n > str.length()){
            return str;
        }
        char[] ch = str.toCharArray();
        reverseString(ch,0,n -1);
        reverseString(ch,n,str.length()-1);
        reverseString(ch,0,str.length()-1);
        return new String(ch);
    }
    public void reverseString(char[] ch,int start,int end){
        while(start < end){
            char temp = ch[start];
            ch[start] = ch[end];
            ch[end] = temp;
            start = start + 1;
            end = end - 1;
        }
    }
}

  Running time: 17ms

  Take up memory: 9668k

Guess you like

Origin www.cnblogs.com/maohaitao/p/11286637.html