另类题解, 使用正则表达式regex
万万没想到之聪明的编辑
https://www.nowcoder.com/practice/42852fd7045c442192fa89404ab42e92
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 int length = in.nextInt(); String emm = in.nextLine();//我不知道为什么第二行输入有个空行。。。 while (in.hasNextLine()) { // 注意 while 处理多个 case String str = in.nextLine(); Check(str); } } public static void Check(String str) { // 检查是否有三个及以上同样的字母连在一起 if (str.matches(".*([A-Za-z])\\1{2,}.*")) { // 保留两个就行 while (str.matches(".*([A-Za-z])\\1{2,}.*")) { str = str.replaceFirst("([A-Za-z])\\1{2,}", "$1$1"); } } // 检查是否两对一样的字母(AABB)连在一起, \\1{1,}表示第一个括号里的内容重复一次或多次 if (str.matches(".*([A-Za-z])\\1{1,}([A-Za-z])\\2{1,}.*")) { // 保留两个就行 while (str.matches(".*([A-Za-z])\\1{1,}([A-Za-z])\\2{1,}.*")) { str = str.replaceFirst("([A-Za-z])\\1{1,}([A-Za-z])\\2{1,}", "$1$1$2"); } } if (str == null || str == " ") { return; } System.out.println(str); } }#23届找工作求助阵地#