首页 > 代码库 > Leetcode: Reverse Words in a String
Leetcode: 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".click to show clarification.Clarification: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.
这道题很直接的想法就是用String的split函数,把字符串按空格分成一个个子字符串,存到一个String[] strs里面,这时再把strs里的字符串从大到小反转连接,中间加上空格就好了。需要注意如果原来的字符串有multiple spaces, 那会造成我们strs数组里面有一些子字符串是空字符串,我们反转时若遇到这些空字符串,就要把它跳过。时间上split操作是O(N),再一次扫描获得结果,也是O(N)。空间上使用了一个String[] 和StringBuffer,也是O(N)
本题就是需要注意一些语法,比如split函数的参数是String而不能是Char。我写的时候不小心再一次犯了低级错误,String判断是不是空字符串一定不要写成if (str == ""), 要么用equals(), 要么用length()==0来判断
1 public class Solution { 2 public String reverseWords(String s) { 3 if (s==null || s.length()==0) return s; 4 s.trim(); 5 String[] strs = s.split(" "); 6 StringBuffer res = new StringBuffer(); 7 for (int i=strs.length-1; i>=0; i--) { 8 if (strs[i].length() == 0) continue; 9 res.append(strs[i]);10 res.append(‘ ‘);11 }12 return res.toString().trim();13 }14 }
Leetcode: Reverse Words in a String
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。