题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
我本地的JDK是16 下面这个正则表达式 分词是没有问题的
// [I, am, a, student] System.out.println(Arrays.toString("I am a student.".split("[^[a-zA-Z]]+")));但是牛客的JDK是 1.8 分词是有问题的
// [, , , , .] System.out.println(Arrays.toString("I am a student.".split("[^[a-zA-Z]]+")));改成下面这样就行
import java.util.*; /** * @author hll[yellowdradra@foxmail.com] * @date 2022-09-30 15:53 **/ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); Arrays.stream(in.nextLine() // 分割字符串得到一个单词数组 .split("[^a-zA-Z]+")) // 反转数组 .sorted((x, y) -> -1) // 合并数组 .reduce((x, y) -> x + " " + y) // 打印数组 .map(System.out::printf); } }下面是双指针解法
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); 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); } public static boolean isLetter(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } }