【LeetCode】Reverse Words in a String

来源:互联网 发布:网络监控代理 编辑:程序博客网 时间:2024/05/21 07:13
Reverse Words in a String 
Total Accepted: 357 Total Submissions: 2355 My Submissions
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.
【解题思路】
1、扫描字符串,按照字符去处理,遇到空格则之前为一个完整的字符串。全部放入list,最后逆序返回。
2、替换掉字符串前后的空白,将中间的多个空格替换为一个,按照正则空格分隔为字符串,逆序返回。

Java AC 1

public class Solution {    public String reverseWords(String s) {        if(s == null || "".equals(s.trim())){            return s.trim();        }        List<String> list = new ArrayList<String>();        s = s.trim();        StringBuffer sb = new StringBuffer();        int i = 0;        int len = s.length();        while(i < len){            sb = new StringBuffer();            while(i < len && s.charAt(i) != ' '){            sb.append(String.valueOf(s.charAt(i)));                i++;            }            while(i < len && s.charAt(i) == ' '){                i++;            }            list.add(sb.toString());        }        int size = list.size();        sb = new StringBuffer();        for(i = size-1; i >= 0; i--){            sb.append(list.get(i)+" ");        }        return sb.toString().trim();    }}

update 2014-06-10

Java AC 2

public class Solution {    public String reverseWords(String s) {s = s.trim().replaceAll("[ ]+", " ");String sArr[] = s.split(java.util.regex.Pattern.quote(" "));StringBuffer sb = new StringBuffer();int len = sArr.length;for (int i = len - 1; i >= 0; i--) {sb.append(sArr[i] + " ");}return sb.toString().trim();}}
Python AC 2

class Solution:    # @param s, a string    # @return a string    def reverseWords(self, s):        sArr = s.strip().split()        slen = len(sArr)        news = ''        for i in range(slen-1, -1, -1):            news += sArr[i]            news += ' '        return news.strip()


0 0