字符遍历判断是否是字母 + 栈

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String input = sc.nextLine();
            Deque<String> wordStack = new LinkedList<>();// stack to hold words
            StringBuilder builder = new StringBuilder();
            for (char c : input.toCharArray()) {
                if (('a' <= c && 'z' >= c) || ('A' <= c && 'Z' >= c))  {
                    builder.append(c);// construct word
                } else {
                    wordStack.push(builder.toString());
                    builder.setLength(0);// clear StringBuilder
                }
            }
            wordStack.push(builder.toString());
            System.out.print(String.join(" ", wordStack));// connect words with "space"
        }
    }
}