Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
public class Solution {
public String reverseWords(String s) {
StringBuffer sb=new StringBuffer("");
StringBuffer revStr=new StringBuffer("");
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=' '){
sb.append(s.charAt(i));
}
else if(i<s.length()-1 && s.charAt(i+1)==' '){
continue;//一般空格也应该反转的,但题目应该是默认合并多个空格,且去掉首尾的空格
}
else{
revStr.append(sb.reverse());
revStr.append(s.charAt(i));
sb=new StringBuffer("");
}
}
revStr.append(sb.reverse());
return revStr.reverse().toString().trim();
}
}
本文介绍了一种用于将输入字符串中的单词进行反转的算法实现。通过使用StringBuffer来逐字符读取原始字符串,并根据空格判断单词边界,实现单词级别的反转。最终返回去除多余空格的反转后字符串。
501

被折叠的 条评论
为什么被折叠?



