Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
41 lines (41 loc) · 1.08 KB

File metadata and controls

41 lines (41 loc) · 1.08 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
34
35
36
37
38
39
40
41
package LeetCodeOJ;
/*
* Reverse Words in a String II leetcode 186
* For example,
"the sky is blue",
"blue is sky the".
*/
public class reverseII {
/**
* 思想就是利用旋转的方法,组个单词翻转
* @param str
* @return
*/
public static String reverseStr(String str){
char [] ch = str.toCharArray();
swap(ch, 0, ch.length - 1);
int space = -1;
for (int i = 0; i < ch.length; i++) {
if(ch[i] == ' '){
int nextSpace = i;
swap(ch, space+1, nextSpace - 1);
space = nextSpace;
}
}
swap(ch, space+1, ch.length - 1);
return new String(ch);
}
public static void swap(char [] ch, int start, int end ){
while(start < end){
char tmp = ch[start];
ch[start] = ch[end];
ch[end] = tmp;
start++;
end--;
}
}
public static void main(String[] args) {
String input = "Let's take LeetCode contest";
System.out.println(reverseStr(input));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.