File tree 1 file changed +38
-0
lines changed 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -475,7 +475,45 @@ class Solution:
475
475
words = words[::- 1 ] # 反转单词
476
476
return ' ' .join(words) # 列表转换成字符串
477
477
```
478
+ (版本四) 将字符串转换为列表后,使用双指针去除空格
479
+ ``` python
480
+ class Solution :
481
+ def single_reverse (self , s , start : int , end : int ):
482
+ while start < end:
483
+ s[start], s[end] = s[end], s[start]
484
+ start += 1
485
+ end -= 1
478
486
487
+ def reverseWords (self , s : str ) -> str :
488
+ result = " "
489
+ fast = 0
490
+ # 1. 首先将原字符串反转并且除掉空格, 并且加入到新的字符串当中
491
+ # 由于Python字符串的不可变性,因此只能转换为列表进行处理
492
+ s = list (s)
493
+ s.reverse()
494
+ while fast < len (s):
495
+ if s[fast] != " " :
496
+ if len (result) != 0 :
497
+ result += " "
498
+ while s[fast] != " " and fast < len (s):
499
+ result += s[fast]
500
+ fast += 1
501
+ else :
502
+ fast += 1
503
+ # 2.其次将每个单词进行翻转操作
504
+ slow = 0
505
+ fast = 0
506
+ result = list (result)
507
+ while fast <= len (result):
508
+ if fast == len (result) or result[fast] == " " :
509
+ self .single_reverse(result, slow, fast - 1 )
510
+ slow = fast + 1
511
+ fast += 1
512
+ else :
513
+ fast += 1
514
+
515
+ return " " .join(result)
516
+ ```
479
517
### Go:
480
518
481
519
版本一:
You can’t perform that action at this time.
0 commit comments