Reverse word order

Reverse word order

Insert image description here

1. Method 1 (Use the characteristics of stringBuffer to solve)

class Solution {
    
    
    public String reverseWords(String s) {
    
    
        String[] s1 = s.replaceAll("\\s{1,}"," ").trim().split(" ");//把多个空格变为一个空格,并删除首尾空格。
        StringBuffer stringBuffer = new StringBuffer();
            for (int i = s1.length - 1; i >= 0 ; i--){
    
    
                stringBuffer.append(s1[i] + " ");
            }
        return stringBuffer.toString().trim();
    }
}

2. Double pointer solution

class Solution {
    
    
    public String reverseWords(String s) {
    
    
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
    
    
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}

Guess you like

Origin blog.csdn.net/qq_45372719/article/details/109585198