There is a shift instruction in assembly language called
循环左移
(ROL). Now there is a simple task, which is to simulate the operation result of this instruction with a string. For a given character sequence S, please rotate it to the left by K bits and output the sequence. For example, the character sequence S="abcXYZdef", it is required to output the result of the circular shift left by 3 bits, that is, "XYZdefabc". Is not it simple? OK, get it done!
Method 1 : UseString
public class Solution {
public String LeftRotateString(String str, int n) {
int len = str.length();
String res = "";
if(len == 0 || str == null) return res;
int n_true = n % len;
for(int i = n_true; i < len; i++){
res += str.charAt(i);
}
for(int i = 0; i < n_true; i++){
res += str.charAt(i);
}
return res;
}
}
In fact, it can be like this:
public class Solution {
public String LeftRotateString(String str, int n) {
String res = "";
for(int i = n; i < n + str.length(); i++){
res += str.charAt(i % str.length());
}
return res;
}
}
Time complexity: O(N)
Space complexity: O(N)
Method two : useStringBuilder
String
Splicing will produce many "fragments", useStringBuilder
public class Solution {
public String LeftRotateString(String str, int n) {
int len = str.length();
String res = "";
if(len == 0 || str == null) return res;
int n_true = n % len;
StringBuilder stringBuilder = new StringBuilder();
for(int i = n; i < n + str.length(); i++){
stringBuilder.append(str.charAt(i % str.length()));
}
res = stringBuilder.toString();
return res;
}
}
Time complexity: O(N)
Space complexity: O(N)
Method 3 : String slicing
public class Solution {
public String LeftRotateString(String str,int n) {
if(str.length() == 0 || str == null) return str;
return str.substring(n, str.length()) + str.substring(0, n);
}
}
Time complexity: O(N)
Space complexity: O(N)
Method 4 : Use the flip function
First 0 - (n-1)
flip, then n-(length-1)
flip, and finally 0-(length-1)
flip
For example: string "abc123"
,n = 3
-
First
0 - 2
turn the flip into"cba123"
; -
Then
3-5
flip turns"cba321"
; -
Finally, the
0-5
flip becomes"123abc"
;
import java.util.Arrays;
public class Solution {
public static String LeftRotateString(String str, int n) {
if(str.length() == 0 || str == null) return str;
str = reverse(str, 0 , n-1);
str = reverse(str, n , str.length()-1);
str =reverse(str, 0 , str.length()-1);
return str;
}
private static String reverse(String str, int startIndex, int endIndex){
char[] chars = str.toCharArray();
while(startIndex < endIndex){
char temp = chars[startIndex];
chars[startIndex] = chars[endIndex];
chars[endIndex] = temp;
startIndex++;
endIndex--;
}
str = new String(chars);
return str;
}
}
Time complexity: O(N)
Space complexity: O(N)