Reverse Words in a String
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
使用API
复杂度
时间 O(N) 空间 O(N)
思路
将单词根据空格split开来存入一个字符串数组,然后将该数组反转即可。
注意
先用trim()将前后无用的空格去掉
用正则表达式" +"来匹配一个或多个空格
代码
public class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split(" +");
int len = words.length;
StringBuilder result = new StringBuilder();
for(int i = len -1; i>=0;i--){
result.append(words[i]);
if(i!=0) result.append(" ");
}
return result.toString();
}
}
双指针交换法
复杂度
时间 O(N) 空间 O(N) 如果输入时char数组则是O(1)
思路
先将字符串转换成char的数组,然后将整个数组反转。然后我们再对每一个单词单独的反转一次,方法是用两个指针记录当前单词的起始位置和终止位置,遇到空格就进入下一个单词。
代码
public class Solution {
public String reverseWords(String s) {
s = s.trim();
char[] str = s.toCharArray();
// 先反转整个数组
reverse(str, 0, str.length - 1);
int start = 0, end = 0;
for(int i = 0; i < s.length(); i++){
if(str[i]!=' '){
end++;
} else {
// 反转每个单词
reverse(str, start, end - 1);
end++;
start = end;
}
}
return String.valueOf(str);
}
public void reverse(char[] str, int start, int end){
while(start < end){
char tmp = str[start];
str[start] = str[end];
str[end] = tmp;
start++;
end--;
}
}
}
Reverse Words in a String II
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example, Given s = "the sky is blue", return "blue is sky the".
Could you do it in-place without allocating extra space?
双指针交换法
复杂度
时间 O(N) 空间 O(1)
思路
这题就是Java版的Inplace做法了,先反转整个数组,再对每个词反转。
代码
public class Solution {
public void reverseWords(char[] s) {
reverse(s, 0, s.length - 1);
int start = 0;
for(int i = 0; i < s.length; i++){
if(s[i] == ' '){
reverse(s, start, i - 1);
start = i + 1;
}
}
reverse(s, start, s.length - 1);
}
public void reverse(char[] s, int start, int end){
while(start < end){
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。