[LeetCode]Reverse Words in a String I II

Reverse Words in a String I

题目描述

Given an input string, reverse the string word by word.

For example,
Given s = “the sky is blue”,
return “blue is sky the”.

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution{

//考虑前导空格、words之间多个空格
public String reverseWords(String s) {
if(s == null || s.length() == 0) return "";

//一个空格或多个空格split
String[] strs = s.trim().split("\s+");

StringBuilder sb = new StringBuilder();
for(int i = strs.length - 1; i > 0; i--){
sb.append(strs[i] + " ");
}
sb.append(strs[0]);
return sb.toString();
}
}

还有一种方法就是逆序遍历字符串,使用两个指针追踪words的开始和结尾,当我们遍历到words的开始时,将words append到结果中。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution{
public String (String s){
if(s == null || s.length() == 0) return "";

StringBuilder sb = new StringBuilder();
//j指针初始指向字符串最后一个字符的下一位置,在每一次迭代中j指向上一个遍历的空格
int大专栏  [LeetCode]Reverse Words in a String I II> j = s.length();
for(int i = s.length() - 1; i >= 0; i--){
//遍历到空格,更新j的指向,指向新的空格
if(s.charAt(i) == ' '){
j = i;
}else if(i == 0 || s.charAt(i - 1) == ' '){//charAt(i - 1) == ' '说明i当前指向某个word的开头,可以获取到该word
if(sb.length() != 0){
sb.append(" ");
}
sb.append(s.substring(i, j));
}
//其他情况直接跳过
}

return sb.toString();
}
}

Reverse Words in a String II

题目描述

Similar to Question [Reverse Words in a String], but with the following constraints:
“The input string does not contain leading or trailing spaces and the words are always separated by a single space.”
Could you do it in-place without allocating extra space?

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//将整个字符串翻转,然后将每个word翻转
public void (char[] s){
reverse(s, 0, s.length - 1);
//j指向每个word的开始
for(int i = 0, j = 0; i < s.length; i++){
if(i == s.length - 1 || s[i] == ' ' ){
reverse(s, j, i);
j = i+1;
}
}
}

public void reverse(char[] s, int start, int end){
while(start < end){
char temp = s[end];
s[end] = s[start];
s[start] = temp;
}
}

你可能感兴趣的:([LeetCode]Reverse Words in a String I II)