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
".Naive Way: 如果能使用String.split()就会很方便。
如答案所说,使用String.split() 是需要两次扫描的。如果从后往前扫String,就只需要一次扫面。
public class Solution {
public String reverseWords(String s) {
StringBuilder rslt = new StringBuilder();
String[] str = s.split(" ");
for(int i = str.length-1;i >= 0;i--){
if(i!=str.length-1 && str[i].length()!=0) rslt.append(" ");
rslt.append(str[i]);
}
return rslt.toString();
}
}
这次从后往前扫,只需要一次。
public class Solution {
public String reverseWords(String s) {
StringBuilder rslt = new StringBuilder();
int i = s.length(), j = s.length();
while(--i >= -1){
if(i==-1 || s.charAt(i) == ' '){
if(i+1!=j && rslt.length()!=0) rslt.append(" ");
rslt.append(s.substring(i+1,j));
j = i;
}
}
return rslt.toString();
}
}
No comments:
Post a Comment