【题目】
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
- What constitutes a word?
A sequence of non-space characters constitutes a word. - Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces. - How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
【题解】
1.遇到空格就跳过,第一个不是空格的元素,位置用pos记录。
2. 即pos之后,继续,只要不是空格,i++
3.当遇到的是第一个单词,即res长度为0时,直接添加,否则,添加“ ”,然后再在前面添加新的单词,达到reverse的效果,res= s.substring(pos,i),+res;注意顺序
4.i-- 因为在检查是否空格那里i++了
注意:substring函数,start是包含的,而end的标是达不到的;
用+重新赋值的好处是可以直接把新的单词调整到最前面,但是这样的做法是不是要耗费的空间比较大。得是单词数目+空格数目。基本是2倍单词数量。
【代码】
public static String solution(String s){
String res= "";
for(int i=0;i<s.length();i++){
if(s.charAt(i)==' ') continue;
int pos=i;
while(i<s.length()&&s.charAt(i)!=' ') i++;
if(res.length()>0) res=" "+res;
res=(s.substring(pos,i))+res;
i--;
}
return res;
}
【官方题解】
One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.
We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.
public class Solution {
public String reverseWords(String s) {
String[] a=s.trim().split("\\s+");
StringBuilder res=new StringBuilder();
for(int i=a.length-1;i>=0;i--){
if(i==a.length-1)res.append(a[i]);
else res.append(" ").append(a[i]);
}
return res.toString();
}
}
\\s+:
split public String[] split(String regex)根据给定的正则表达式的匹配来拆分此字符串。 然后就要明确正则表达式的含义了: \\s表示 空格,回车,换行等空白符, +号表示一个或多个的意思,所以...