Problem Description
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
Hint
The string “Pirates”, can type this way, Shift, p, i, r, a, t, e, s, the answer is 8.
The string “HDUacm”, can type this way, Caps lock, h, d, u, Caps lock, a, c, m, the answer is 8
The string “HDUACM”, can type this way Caps lock h, d, u, a, c, m, Caps lock, the answer is 8
题意:给你一个字符串,输出在键盘上输入它的最少按键次数,注:键盘的初始状态和最后状态都要是小写。
解题思路:枚举所有字母用小写和大写锁定情况输入的情况并取最小值。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int dp1[105],dp2[105],n;///dp1表示键盘是小写状态,dp2表示键盘是大写状态
string str;
cin>>n;
while(n--){
cin>>str;
memset(dp1,0,sizeof(dp1));
memset(dp2,0,sizeof(dp2));
dp2[0] = 1;///因为最开始和最后键盘都是小写状态,所以大写状态的 最开始要要赋值为1,最后也要加一
int len = str.length();
for(int i=0;i<len;i++){
if(str[i]>='a'&&str[i]<='z'){
dp1[i+1]=min(dp1[i]+1,dp2[i]+2);///键盘始终保持小写,若当前字母是小写上个字母也是小写所以dp1[i]+1,若当前字母是小写上个字母是大写需要按shift+这个字母所以dp2[i]+2;
dp2[i+1]=min(dp1[i]+2,dp2[i]+2);///键盘始终保持大写,若当前字母是小写上个字母也是小写所以在按下小写字母后还要让键盘保持大写状态所以dp1[i]+2,若当前字母是小写上个字母是大写当前键盘环境为为大写所以输入一个小写字母需要按两次所以dp2[i]+2;
}
else{
dp1[i+1]=min(dp1[i]+2,dp2[i]+2);///键盘始终保持小写,若当前字母是大写上个字母是小写键盘为小写状态dp1[i]+2,若当前字母是大写上个字母也是大写需要按下这个字母并将键盘恢复到小写状态所以dp2[i]+2;
dp2[i+1]=min(dp1[i]+2,dp2[i]+1);///键盘始终保持大写,若当前字母是大写上个字母是小写所以需要按shift+这个字母所以dp1[i]+2,若当前字母是大写上个字母也是大写可直接按下所以dp2[i]+1;
}
int ans = min(dp1[len],dp2[len]+1);
cout<<ans<<endl;
}
return 0;
}