for(int i=2;i<word.length();)
最开始 是 i< len
但是word.length()是变化的 因此不能是len 需要注意
import java.util.Scanner; import java.util.*; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); sc.nextLine(); for(int i=0;i<n;i++){ String res = ParseWord(sc.nextLine()); System.out.println(res); } } public static String ParseWord(String word){ int len = word.length(); if(len < 3) return word; for(int i=2;i<word.length();){ if(word.charAt(i-2) == word.charAt(i-1) && word.charAt(i-1) == word.charAt(i)){ word = word.substring(0,i-1) + word.substring(i,word.length()); } else if(i>2 && word.charAt(i-3) == word.charAt(i-2) && word.charAt(i-1) == word.charAt(i) ){ word = word.substring(0,i-1) + word.substring(i,word.length()); } else i++; } return word; } }