Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
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.
My Answer:
public class Solution {
public String reverseWords(String s) {
String[] array = s.split(" ");
StringBuilder builder = new StringBuilder();
String space = " ";
int length = array.length - 1;
for(int i = length; i >= 0; i--){
String cleanStr = array[i].trim();
if(cleanStr.length() == 0){
continue;
}
builder.append(cleanStr);
builder.append(space);
}
return builder.toString().trim();
}
}

本文介绍了一种使用Java实现的方法,该方法可以将输入字符串中的单词顺序进行反转,同时处理了单词之间的多余空格及前后空白字符的问题。
568

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



