码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Reverse Words in a String

时间:2014-10-12 02:03:07      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   使用   ar   java   

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

标签:style   blog   http   color   io   os   使用   ar   java   

原文地址:http://www.cnblogs.com/EdwardLiu/p/4019970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!