Reverse Words in a String I
https://leetcode.com/problems/reverse-words-in-a-string/
这道题O(n)的方法很简单,就是遍历字符串,找到一个词就放到list里面,遍历完后把list里面的单词从后往前连起来就行。
而且本来我想用JAVA的s.split(" ")函数的,结果leetcode的用例全部都是不规律的,两个单词间N多空格,或者字符串前后都是空格之类的,所以用split是分不干净的,还是得自己遍历字符串。
O(1)的方法需要把string转化成char array,但是对于JAVA来说,这样本身就已经用了额外的内存了。
对于C, C++来说,在char array里面,先把多余的space去掉,保证首尾没有,两个单词之间只有一个。然后先reverse整个string,再reverse每个单词。
这里只写了第一种方法:
public String reverseWords(String s) {
int i = 0;
ArrayList<String> words = new ArrayList<String>();
while(i<s.length()){
while(i<s.length() && s.charAt(i)==' ') i++;
if(i==s.length()) break; //注意这里,空格后面已经没有字母了
int start = i;
while(i<s.length() && s.charAt(i)!=' ') i++;
words.add(s.substring(start, i));
}
StringBuilder sb = new StringBuilder();
for(i=(words.size()-1); i>=0; i--){
sb.append(words.get(i));
if(i!=0) sb.append(' ');
}
return sb.toString();
}
Reverse words in a String II:
https://leetcode.com/problems/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?
Related problem: Rotate Array
这道题跟上一道题一样,只不过现在输入的是一个char array,然后要求reverse in place,所以就像上面说的方法,先reverse整个数组,再reverse每个单词就可以了:public class Solution {
public void reverseWords(char[] s) {
reverse(s, 0, s.length-1);
for(int i=0; i<s.length; i++){
int start = i;
while(i<s.length && s[i]!=' ') i++;
reverse(s, start, i-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--;
}
}
}
这里的空间复杂度就是O(1)了,时间复杂度O(n)