【leetcode】Reverse Words in a String(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".

For C programmers: Try to solve it in-place in O(1) space.

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的String自带的方法很好解决。

解题思路:

思路就是用split方法分割String为数组,再倒序排列。

部分细节:trim方法去除首尾空格;数组中为空的是表示有连续空格,不处理;只含空格的string单独处理(split后数组长度为0)。

public class Solution {
    public String reverseWords(String s) {
        if(s == null)
            return null;
        if(s.equals(""))
            return "";
        String temp = s.trim();
        String[] str = temp.split(" ");
        if(str.length == 0)
            return "";
        StringBuilder res = new StringBuilder();
        for(int i = str.length - 1; i > 0; i--){
            if((!str[i].equals(""))&&(str[i]!=null)){
                res.append(str[i]);
                res.append(" ");
            }
        }
        if((!str[0].equals(""))&&(str[0]!=null))
            res.append(str[0]);
        
        return res.toString();
    }
}

效率方面beats 85.88%,还可以吧。

你可能感兴趣的:(java,LeetCode)