一次遍历,考虑状态
用一个temp缓存字符子串,长度不超过3,比较当前字符与上一个字符是否相等
temp只有这几5种情况={空,a,aa,aab}
加上当前字符有这么几种状态{a,aa,aaa,ab,aab,aabb,aabc},但是可以合并,代码如下
package org.niuke.solution67;
import java.util.*;
public class Main {
private static String solve(String s){
Queue<Character> queue = new LinkedList<>();
String res = "", temp = "";
int pre = 0;
for(int i = 0; i < s.length(); i++){
queue.offer(s.charAt(i));
}
while (!queue.isEmpty()) {
int last = temp.length() - 1;
Character c = queue.poll();
if(last < 0){
temp += c;
pre++;
}else{
if(c == temp.charAt(last)){
if(pre < 2){//bb 只有
pre++;
temp += c;
}else if(pre == 2){ //aab,aaa 都是直接丢弃
continue;
}
}else{//ab aabc,aab
if(pre < 2){
res += temp;
temp = "" + c;
pre = 1;
}else{
if(temp.length() < 3){
temp += c;
}else{
res += temp;
temp = "" + c;
pre = 1;
}
}
}
}
}
return res + temp;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
while (n > 0) {
n--;
String res = solve(scanner.nextLine());
System.out.println(res);
}
}
} 
京公网安备 11010502036488号