leetcode解题方案--151--Reverse Words in a String

来源:互联网 发布:linux运维基础知识 编辑:程序博客网 时间:2024/06/03 13:01

听某人的话,从靠后一点的位置开始
这样的话到过年的时候就可以首尾相连了吧

题目

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.

分析

两个单词之间可能有多个space
字符串左右起始位置可能有space
这道题最简单的方法是用split
但是我没有
思路是用一个栈把string放进去
然后再弹出来。

public static String reverseWords(String s) {        System.out.print(Arrays.toString(s.split(" ")));        if (s.length()<=0){            return "";        }        char[] xx = s.trim().toCharArray();        StringBuffer word = new StringBuffer("");        Stack stack = new Stack<String>();        boolean isWord= true;        for (int i = 0; i<xx.length;i++) {            if (xx[i] != ' ') {                isWord = true;                word.append(xx[i]);            } else if (xx[i] == ' ' && isWord){                stack.push(word.toString());                isWord = false;                word = new StringBuffer("");            } else if (xx[i] == ' '&& !isWord) {            }        }        if (word.toString().length()!=0) {            stack.push(word.toString());        }        StringBuffer ret = new StringBuffer("");        while (!stack.empty()) {            ret.append(stack.pop());            ret.append(" ");        }        System.out.println(ret);        if (ret.length() >= 1) {            return ret.toString().substring(0,ret.length()-1);        } else{            return "";        }    }
原创粉丝点击