leetcode 151. Reverse Words in a String 字符串 翻转

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a1b2c3d4123456/article/details/52152737

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

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

思路:按照空格分割后存到字符串数组里,然后从后向前遍历存储,需要注意前面的空格和后面的空格。
注意区分“”和“ ”的区别。

package test;

public class str {
    public static String reverseWords(String s) {
        if (s == null) {
            return "";
        }
        String[] array = s.split(" ");
        StringBuilder res = new StringBuilder();
        for (int i = array.length - 1; i >= 0; i--) {
            if (!"".equals(array[i])) {
                res.append(array[i]);
                res.append(" ");
            }
        }
        return res.length() == 0 ? "" : res.substring(0, res.length() - 1)
                .toString();
    }

    public static void main(String[] args) {
        System.out.print(reverseWords("     f ttt t "));
    }
}

猜你喜欢

转载自blog.csdn.net/a1b2c3d4123456/article/details/52152737