码迷,mamicode.com
首页 > 编程语言 > 详细

[Leetcode][JAVA] Reverse Words in a String

时间:2014-09-09 12:07:48      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   java   ar   strong   for   数据   

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

 

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.

 

用JAVA或Python有简便方法:

这是我最开始AC的代码,用split()方法:

 

public String reverseWords(String s) {
        String[] token = s.split(" ");
        String re = "";
        for(int i=token.length;i>0;i--)
        {
            if(token[i-1].compareTo("")!=0)
                re = re + token[i-1] + " ";
        }
        return re.trim();
    }


后来看discuss说是cheat,就改成:

 

public String reverseWords(String s) {
        ArrayList<String> ls = new ArrayList<String>();
        int i=0;
        while(i<s.length())
        {
            if(!(s.charAt(i)==‘ ‘))
            {
                int j=i;
                String temp = "";
                while(j<s.length() && !(s.charAt(j)==‘ ‘))
                {
                    temp+=s.charAt(j);
                    j++;
                }
                ls.add(temp);
                i=j;
            }
            else
                i++;
        }
        
        String re = "";
        for(int j=ls.size()-1;j>=0;j--)
        {
            re = re + ls.get(j) + " ";
        }
        return re.equals("")?re:re.substring(0,re.length()-1);
    }

 

 

遇到非空格就往下扫描,直到遇到空格或扫描至字符串末尾,则可以获得一个完整的词。
拿一个数据结构(这里用ArrayList)保存截取下来的词,然后从后往前输出。

最后需要把可能存在的末尾空格去掉。

 

[Leetcode][JAVA] Reverse Words in a String

标签:style   blog   color   io   java   ar   strong   for   数据   

原文地址:http://www.cnblogs.com/splash/p/3962006.html

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