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

Sign up
Appearance settings

Commit e9a164a

Browse files
update:0151.翻转字符串里的单词.md java 版本,增加解法四
时间复杂度 O(n) 参考卡哥 c++ 代码的实现:先移除多余空格,再将整个字符串反转,最后把单词逐个反转
1 parent f55786b commit e9a164a

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

‎problems/0151.翻转字符串里的单词.md‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,74 @@ class Solution {
360360
}
361361
```
362362

363+
```java
364+
/*
365+
* 解法四:时间复杂度 O(n)
366+
* 参考卡哥 c++ 代码的实现:先移除多余空格,再将整个字符串反转,最后把单词逐个反转
367+
*/
368+
class Solution {
369+
//用 char[] 来实现 String 的 removeExtraSpaces,reverse 操作
370+
public String reverseWords(String s) {
371+
char[] chars = s.toCharArray();
372+
//1.去除首尾以及中间多余空格
373+
chars = removeExtraSpaces(chars);
374+
//2.整个字符串反转
375+
reverse(chars, 0, chars.length - 1);
376+
//3.单词反转
377+
reverseEachWord(chars);
378+
return new String(chars);
379+
}
380+
381+
//1.用 快慢指针 去除首尾以及中间多余空格,可参考数组元素移除的题解
382+
public char[] removeExtraSpaces(char[] chars) {
383+
int slow = 0;
384+
for (int fast = 0; fast < chars.length; fast++) {
385+
//先用 fast 移除所有空格
386+
if (chars[fast] != ' ') {
387+
//在用 slow 加空格。 除第一个单词外,单词末尾要加空格
388+
if (slow != 0)
389+
chars[slow++] = ' ';
390+
//fast 遇到空格或遍历到字符串末尾,就证明遍历完一个单词了
391+
while (fast < chars.length && chars[fast] != ' ')
392+
chars[slow++] = chars[fast++];
393+
}
394+
}
395+
//相当于 c++ 里的 resize()
396+
char[] newChars = new char[slow];
397+
System.arraycopy(chars, 0, newChars, 0, slow);
398+
return newChars;
399+
}
400+
401+
//双指针实现指定范围内字符串反转,可参考字符串反转题解
402+
public void reverse(char[] chars, int left, int right) {
403+
if (right >= chars.length) {
404+
System.out.println("set a wrong right");
405+
return;
406+
}
407+
while (left < right) {
408+
chars[left] ^= chars[right];
409+
chars[right] ^= chars[left];
410+
chars[left] ^= chars[right];
411+
left++;
412+
right--;
413+
}
414+
}
415+
416+
//3.单词反转
417+
public void reverseEachWord(char[] chars) {
418+
int start = 0;
419+
//end <= s.length() 这里的 = ,是为了让 end 永远指向单词末尾后一个位置,这样 reverse 的实参更好设置
420+
for (int end = 0; end <= chars.length; end++) {
421+
// end 每次到单词末尾后的空格或串尾,开始反转单词
422+
if (end == chars.length || chars[end] == ' ') {
423+
reverse(chars, start, end - 1);
424+
start = end + 1;
425+
}
426+
}
427+
}
428+
}
429+
```
430+
363431
python:
364432

365433
```Python

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /