本文主要是介绍leetcode151: Reverse Words in a String,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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);}
这篇关于leetcode151: Reverse Words in a String的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!