前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
Clarification:
这个题目也挺简单的,就是有一个地方要注意,通过" "空格去分割的时候会出现""的情况,需要排除一下。
Your runtime beats 90.66% of java submissions.
- 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.
public class Solution {
public String reverseWords(String s) {
String[] splits = s.split(" ");
StringBuffer sb = new StringBuffer("");
if(splits.length > 0 && !splits[splits.length - 1].equals(" ") && !splits[splits.length - 1].equals("") ) sb.append(splits[splits.length -1]);
for(int i = splits.length - 2; i >= 0; i--){
if(!splits[i].equals(" ") && !splits[i].equals("")){sb.append(" ");sb.append(splits[i]);}
}
return sb.toString();
}
}