倒置字符串 151. Reverse Words in a String

这道题比较麻烦的地方是需要用正则表达式,本题中用到了“ +”表示多个空格。
这个解法效率很低但是很简单。

public class Solution {
    public String reverseWords(String s) {
        if(s.length() == 0)
            return "";
        String[] words = s.split(" ");
        String ret = new String();
        for(int i = words.length - 1; i >= 0;i-- ){ 
            ret = ret + words[i] + " ";
        }
        return ret.trim().replaceAll(" +", " ");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44015873/article/details/86367925