翻转字符串里的单词

解法一:字符串遍历
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LeetCode_151 {
    public static String reverseWords(String s) {
        if (s == null || s.length() == 0 || s.trim().length() == 0) {
            return "";
        }
        List<String> words = new ArrayList<>();
        s = s.trim();
        StringBuilder curWord = new StringBuilder();
        char lastChar = ' ';
        for (int i = 0; i < s.length(); i++) {
            char curChar = s.charAt(i);
            if (curChar == ' ' && lastChar == ' ') {
                // 如果当前字符和上一个字符都是空格,则跳过处理下一个字符
                continue;
            } else if (curChar == ' ' && lastChar != ' ') {
                // 如果当前字符是空格而上一个字符不是空格,说明上一个字符是当前单词的结束符号,将该单词添加到单词列表中
                words.add(curWord.toString());
                curWord = new StringBuilder();
                lastChar = ' ';
            } else if (curChar != ' ' && lastChar == ' ') {
                // 如果当前字符不是空格而上一个字符是空格,说明当前字符是单词的开始符号
                curWord.append(curChar);
                lastChar = curChar;
            } else if (curChar != ' ' && lastChar != ' ') {
                // 如果当前字符和上一个字符都不是空格,说明当前单词并未结束
                curWord.append(curChar);
                lastChar = curChar;
            }
        }
        words.add(curWord.toString());

        Collections.reverse(words);
        return String.join(" ", words);
    }

    public static void main(String[] args) {
        // 测试用例,期望输出结果:
        // bob like even not does Alice
        System.out.println(reverseWords("   Alice does not even like    bob   "));
    }
}
03-05 15:34