Pirates have finished developing the typing software. He called Cathy to test his typing software. She is good at thinking. After testing for several days, she finds that if she types a string by some ways, she will type the key at least. But she has a bad habit that if the caps lock is on, she must turn off it, after she finishes typing. Now she wants to know the smallest times of typing the key to finish typing a string.
Input
The first line is an integer t (t<=100), which is the number of test case in the input file. For each test case, there is only one string which consists of lowercase letter and upper case letter. The length of the string is at most 100.
Output
For each test case, you must output the smallest times of typing the key to finish typing this string.
Sample Input
3
Pirates
HDUacm
HDUACM
Sample Output
8
8
8
这题用模拟能做。有队友用模拟a了。第一眼看上去也是模拟,写完之后wa了两发实在找不出错,无奈改dp写法(后来我才想起来大写锁定时按shift可以输小写……我是zz)。
这题的状态转移方程:
if (isUpperCase(a)) {
dp[i][0] = Math.min(dp[i - 1][0] + 2, dp[i - 1][1] + 2);
dp[i][1] = Math.min(dp[i - 1][0] + 2, dp[i - 1][1] + 1);
} else {
dp[i][0] = Math.min(dp[i - 1][0] + 1, dp[i - 1][1] + 2);
dp[i][1] = Math.min(dp[i - 1][0] + 2, dp[i - 1][1] + 2);
}
0位存的是非大写锁定,1位存的是大写锁定状态。然后枚举出所有走法(锁定到非锁定,非锁定到锁定,锁定到锁定,非锁定到锁定)就能写出状态转移方程。
ac代码:
public class Main {
static int[][] dp = new int[105][2];
static String input;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int t = reader.nextInt();
while (t-- > 0) {
input = reader.next();
int n = input.length();
for (int i = 0; i < 105; i++) {
Arrays.fill(dp[i], 0);
}
dp(n);
//这里dp[n][1]还要+1是因为最后必须关掉大写锁定,算一步
System.out.println(Math.min(dp[n][0], dp[n][1] + 1));
}
}
public static void dp(int n) {
dp[0][1] = 1;
for (int i = 1; i <= n; i++) {
char a = input.charAt(i - 1);
if (isUpperCase(a)) {
dp[i][0] = Math.min(dp[i - 1][0] + 2, dp[i - 1][1] + 2);
dp[i][1] = Math.min(dp[i - 1][0] + 2, dp[i - 1][1] + 1);
} else {
dp[i][0] = Math.min(dp[i - 1][0] + 1, dp[i - 1][1] + 2);
dp[i][1] = Math.min(dp[i - 1][0] + 2, dp[i - 1][1] + 2);
}
}
}
public static boolean isUpperCase(char a) {
return a >= 'A' && a <= 'Z';
}
}