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.
- public class Solution {
- public String reverseWords(String s) {
- Stack<Character> word = new Stack<Character>();
- Stack<Character> sentence = new Stack<Character>();
- char[] chars = s.toCharArray();
- for(int i=0;i<=chars.length;i++){
- if(i==chars.length||chars[i]==' '){
- if(!word.isEmpty()){
- if(!sentence.isEmpty()){
- sentence.add(' ');
- }
- while(!word.isEmpty()){
- sentence.add(word.pop());
- }
- }
- }else{
- word.add(chars[i]);
- }
- }
- StringBuilder sb = new StringBuilder();
- while(!sentence.isEmpty()){
- sb.append(sentence.pop());
- }
- return sb.toString();
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46567103