-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeftRotate42.java
More file actions
33 lines (30 loc) · 889 Bytes
/
LeftRotate42.java
File metadata and controls
33 lines (30 loc) · 889 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package offer;
/*
* 左旋转字符串
* abcdef--->defgabc
* n < 0 但是可等于length - 1
*
*/
public class LeftRotate42 {
public void reverse(char[] chars , int s, int e){
while(s < e){
char c = chars[s];
chars[s++] = chars[e];
chars[e--] = c;
}
}
public String LeftRotateString(String str,int n) {
if(str.length() == 0 || n < 0 || n > str.length())
return "";
char [] strRevse = str.toCharArray();
//(aTbT)T == ba
reverse(strRevse, 0 ,n - 1);
reverse(strRevse,n , strRevse.length - 1);
reverse(strRevse, 0 , strRevse.length - 1);
return String.valueOf(strRevse);
}
public static void main(String[] args) {
String str = "abcdefg";
System.out.println(new LeftRotate42().LeftRotateString(str, 3));
}
}