首页 > 代码库 > [Leetcode][JAVA] Reverse Words in a String

[Leetcode][JAVA] 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".

 

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