您的位置:首页 > 其它

leetcode 142: Reverse Words in a String

2014-06-20 05:15 267 查看

Reverse Words in a String

Total Accepted: 17523
Total Submissions: 126756
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

click to show clarification.
Clarification:

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.


// "  fadf the fdasf  fdfaf          "
// "a"

public class Solution {
public String reverseWords(String s) {
if(s==null || s.length() == 0 ) return s;

StringBuilder res = new StringBuilder();
StringBuilder sb = new StringBuilder();
for(int i=0; i<s.length(); i++) {
char c = s.charAt(i);
if( c != ' ' ) {
sb.append(c);
} else if(sb.length()!=0 ) {
res.insert(0, " ");
res.insert(0, sb.toString() );
sb = new StringBuilder();
}
}

if(sb.length()!=0 ) {
res.insert(0, " ");
res.insert(0, sb);
}
return res.length()==0 ? "" : res.substring(0, res.length()-1);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: