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

Reverse Words in a String

时间:2014-07-16 20:46:04      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:blog   java   os   for   io   问题   

源自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".

 

目前被接受的Java代码如下:

public class Solution {
    public String reverseWords(String s) {
        //delete spaces before and after string
        String tmp = s.trim();

        //if no space exists, return original string
        if(s.indexOf(" ") == -1)
        {
            return s;
        }
        //if only spaces exist, return ""
        if(tmp == "")
        {
            return tmp;
        }
        
        //construct a string array has spaceCount+1 elements to store string elements
        String[] strArray = tmp.split("\\s+");
        
        //construct final string in reverse sequence
        StringBuilder result = new StringBuilder();
        result.append(strArray[strArray.length-1].trim());
        for(int i = strArray.length-2; i >= 0; i--)
        {
            if(strArray[i] != null)
            {
                result.append(" " + strArray[i]);
            }
        }
        
        return result.toString();
    }
}

  其中有几个关键问题要注意:

1. 如果s全是空格的情况下,经过trim之后应该是"",此时不应该返回s,而应该返回“”;也就是说很容易遗漏tmp == ""的情况;

2. 在String类中的split函数中,参数\\s表示空格、回车、换行等空白符;+号表示一个或多个;因此根据多个空格符拆分字符串需要用到\\s+;

3. StringBuilder类的append函数相比String类的+ operator效率高很多;

4. 先append最后一个单词,然后开始循环append空格和接下来的单词;

5. 切记toString();

主要用到的String类函数有trim(), indexOf(), split()。split函数需要用到正则表达式,用到的时候再深入学习。

 

Reverse Words in a String,布布扣,bubuko.com

Reverse Words in a String

标签:blog   java   os   for   io   问题   

原文地址:http://www.cnblogs.com/maggieliu/p/3836527.html

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