Skip to content

Commit b6fb6c5

Browse files
committed
Merge branch 'master' of github.com:V1ncentzzZ/leetcode
2 parents 07646c4 + 80baf15 commit b6fb6c5

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
557. 反转字符串中的单词 III
2+
3+
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
4+
5+
示例 1:
6+
7+
输入: "Let's take LeetCode contest"
8+
输出: "s'teL ekat edoCteeL tsetnoc"
9+
注意:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
10+
11+
class Solution {
12+
13+
// https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/submissions/
14+
15+
// TODO 空复O(1) 未AC
16+
// public String reverseWords(String s) {
17+
// s = s.trim();
18+
// if(s.length() < 2) return s;
19+
// char[] wordChar = s.toCharArray();
20+
// String result = "";
21+
// for(int i=0; i<=wordChar.length; i++){
22+
// if(i == wordChar.length || ' ' == wordChar[i]){
23+
// for(int j=i-1; j>=0; j--){
24+
// if(wordChar[j] == ' ' && j != wordChar.length - 1) {
25+
// result += " ";
26+
// break;
27+
// }
28+
// if(j == 0) result += " ";
29+
// // if(result.equals("") && wordChar[j] == ' ') continue;
30+
// // if(j == wordChar.length-1)
31+
// result += wordChar[j];
32+
// }
33+
// continue;
34+
// }
35+
// }
36+
// return result;
37+
// }
38+
39+
40+
public String reverseWords(String s) {
41+
String[] strs = s.split(" ");
42+
StringBuilder sb = new StringBuilder();
43+
for(String str:strs){
44+
char[] chars = str.toCharArray();
45+
for(int i=0,j=chars.length-1;i<j;i++,j--){
46+
char temp = chars[i];
47+
chars[i] = chars[j];
48+
chars[j] = temp;
49+
}
50+
sb.append(new String(chars) + " ");
51+
}
52+
return sb.toString().trim();
53+
}
54+
55+
}

0 commit comments

Comments
 (0)