151. Reverse Words in a String | Java最短代码实现

原题链接: 151. Reverse Words in a String

【思路】

以空格划分数组,然后从数组的最后到开头添加数组到result,最后去除result结尾的空格:

    public String reverseWords(String s) {
        String[] arr = s.split(" ");
        String result = "";
        for (int i = arr.length - 1; i >= 0; i--)
            if (!arr[i].equals(""))
                result += arr[i] + " ";
        return result.trim();
    }
22 / 22  test cases passed. Runtime: 53 ms  Your runtime beats 15.51% of javasubmissions.
欢迎优化!

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