Leetcode-151-翻转字符串里的单词

Leetcode-151-Reverse Words in a String

思路:

题目描述:

翻转字符串里面的单词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.


Example 3:

Input: "a good   example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

Solution1:双指针

分为以下三部分:

  • 翻转整个数组
  • 翻转每个单词
  • 去除单词前后空格

Solution2:使用自带的库

Java

Solution :

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Solution {
public String reverseWords(String s) {
if(s == null) return null;
char[] arr_s = s.toCharArray();
int n = arr_s.length;

// 翻转整个数组
reverse(arr_s,0,n-1);
// 翻转每个单词
word_reverse(arr_s,n);
// 去除多余空格
return clean_space(arr_s,n);
}

private void reverse(char[] arr_s,int i,int j){
while (i < j){
// 交换前后单词顺序
char t = arr_s[i];
arr_s[i++] = arr_s[j];
arr_s[j--] = t;
}
}

private void word_reverse(char[] arr_s, int n) {
int i = 0;
int j = 0;
while (j < n) {
// 找到第一个首字母(如果这个单词是以空格开头)
while (i < n && arr_s[i] == ' ') {
i++;
}
j = i;
// 一直遍历到这个单词末位置
while (j < n && arr_s[j] != ' ') {
j++;
}
reverse(arr_s, i, j - 1);
i = j; // 刷新i的位置,继续遍历
}
}

// 双指针去掉空格
private String clean_space(char[] arr_s,int n){
int i = 0;
int j = 0;
while(j < n){
// 去掉前面的空格
while (j < n && arr_s[j] == ' ') j++;
// 排除单词的长度
while (j < n && arr_s[j] != ' ') arr_s[i++] = arr_s[j++];
// 单词结束还需要去除后面空格
while (j < n && arr_s[j] == ' ') j++;
if (j < n) arr_s[i++] = ' ';
}
return new String(arr_s).substring(0,i);
}
}
1
2
3
4
5
6
7
8
9
10
class Solution{
public String reverseWords(String s){
// 去掉空格(运用正则表达式)
String[] words = s.trim().split(" +");
// 翻转字符
Collections.reverse(Arrays.asList(words));
// 返回字符串结果
return String.join(" ",words);
}
}

Python

Solution :

1
2


打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信