leetcode151: Reverse Words in a String

来源:互联网 发布:小米盒子3破解软件 编辑:程序博客网 时间:2024/05/21 14:43

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.(我用java写的,没有这个要求??)

注意:String转化为String[] 后,空格会变""存在数组中

public String reverseWords(String s) {s = s.trim();if (s.length() == 0)return "";StringBuffer sbf = new StringBuffer(s);s = new String(sbf.reverse());String[] ss = s.split(" ");String re = "";for (int i = 0; i < ss.length; i++) {StringBuffer sb = new StringBuffer(ss[i]);ss[i] = new String(sb.reverse());}for (int i = 0; i < ss.length; i++)if (!ss[i].equals(""))re = re + ss[i] + " ";return re.substring(0, re.length() - 1);}



0 0
原创粉丝点击