题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
给出三种解法,复杂程度依次递增
import java.util.LinkedList; import java.util.Scanner; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { try (Scanner in = new Scanner(System.in)) { String str = in.nextLine(); // solution1(str); // solution2(str); solution3(str); } } private static void solution1(String str) { String[] words = str.split("\\W"); for (int i = words.length - 1; i >= 0; i--) { System.out.print(words[i] + " "); } } private static void solution2(String str) { LinkedList<Character> stack = new LinkedList<>(); for (char c : str.toCharArray()) { boolean isLetter = isLetter(c); if (isLetter) { stack.push(c); } else { if (!stack.isEmpty() && stack.peek() != ' ') { stack.push(' '); } } } StringBuilder sb = new StringBuilder(); LinkedList<Character> wordStack = new LinkedList<>(); while (!stack.isEmpty()) { if (stack.peek() != ' ') { wordStack.push(stack.pop()); } else { while (!wordStack.isEmpty()) { sb.append(wordStack.pop()); } sb.append(stack.pop()); } } while (!wordStack.isEmpty()) { sb.append(wordStack.pop()); } System.out.println(sb.toString().trim()); } private static void solution3(String str) { StringBuilder sb = new StringBuilder(); int len = str.length(), l = 0, r = 0, i = len - 1; while (i >= 0) { while (i >= 0) { if (isLetter(str.charAt(i))) { r = i + 1; break; } i--; } while (i >= 0) { if (!isLetter(str.charAt(i))) { l = i + 1; i--; break; } if (isLetter(str.charAt(i)) && i == 0) { l = 0; i--; break; } i--; } sb.append(str, l, r).append(" "); } System.out.println(sb); } private static boolean isLetter(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } }