首页 > 代码库 > hihoCoder 1039 字符消除

hihoCoder 1039 字符消除

题目来源:字符消除

解题思路:

1、在给定字符串中的任意位置插入‘A‘、‘B‘、‘C‘中的任意一个字符,然后计算插入后的字符经过消除后最短的字符串长度;

2、在计算字符消除后最短长度时,智能一遍一遍的计算,个人没有想出什么更好地方法

3、记录每次插入一个字符后经过第2步计算后最短的字符串长度min,最后原字符串的长度-min+1。

 

具体算法(java版,可以直接AC)

 

 1 import java.util.Scanner; 2  3 public class Main { 4  5     public static int handle(StringBuffer buffer) { 6         int count = 0; 7         while (true) { 8             StringBuffer temp = new StringBuffer(); 9             int i = 0, j = 1;10             for (; j < buffer.length(); j++) {11                 if (buffer.charAt(i) != buffer.charAt(j)) {12                     temp.append(buffer.charAt(i));13                 } else {14                     while (j < buffer.length()15                             && buffer.charAt(i) == buffer.charAt(j))16                         j++;17                 }18                 i = j;19             }20             if (j == buffer.length()) {21                 temp.append(buffer.charAt(i));22             }23             if (temp.length() == buffer.length()) {24                 count = temp.length();25                 break;26             }27             buffer = temp;28         }29         return count;30     }31 32     public static void main(String[] args) {33         Scanner scanner = new Scanner(System.in);34         int n = scanner.nextInt();35         for (int i = 0; i < n; i++) {36             StringBuffer buffer = new StringBuffer(scanner.next());37             int min = buffer.length();38             for (int j = 0; j < buffer.length(); j++) {39                 for (char ch = ‘A‘; ch <= ‘C‘; ch++) {40                     StringBuffer temp = new StringBuffer(buffer);41                     temp = temp.insert(j, ch);42                     int count = handle(temp);43                     min = min > count ? count : min;44                 }45             }46             System.out.println(buffer.length() + 1 - min);47         }48     }49 }

 

hihoCoder 1039 字符消除