在计算机键盘上输出一串字符需要一定的按键数目。假定初始为小写字母状 态,结束之后也必须回到小写字母状态。例如,在输入字符串“Pirates”时, 需要先按下 Shift+P,再依次按下 i,r,a,t,e,s,一共需要按 8 次键。下面输出若 干个字符串,求它们的最少按键次数。 输入格式: 第一行为正整数 t(≤10),表示测试数据组数,接下来 t 行,每行一个不长 度不超过 100000 的字符串。 输出格式: 对于每组数据,输出一个正整数表示最少按键次数 c++ 显示一秒 暴力解决
时间: 2024-04-15 21:31:28 浏览: 184
如果要使用暴力解决这个问题,可以尝试列举出所有可能的按键序列,然后计算每个序列的按键次数,最后找到最小的按键次数。以下是一个示例的暴力解决方法:
```cpp
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int getKeyPressCount(string str) {
int minCount = INT_MAX;
int len = str.length();
for (int i = 0; i < pow(2, len); i++) {
int count = 0;
bool shiftPressed = false;
for (int j = 0; j < len; j++) {
if (isupper(str[j]) && !shiftPressed) {
count += 2;
shiftPressed = true;
} else if (islower(str[j]) && shiftPressed) {
count += 2;
shiftPressed = false;
} else {
count += 1;
}
}
minCount = min(minCount, count);
}
return minCount;
}
int main() {
int t;
cin >> t;
while (t--) {
string str;
cin >> str;
int count = getKeyPressCount(str);
cout << count << endl;
}
return 0;
}
```
这段代码使用了两个嵌套循环,外层循环用于遍历每个测试数据,内层循环用于遍历所有可能的按键序列。在内层循环中,根据当前字符的大小写以及前一个字符是否是大写字母来判断是否需要按Shift键。最后,通过比较得到最小的按键次数。
需要注意的是,由于这是一个暴力解决方法,对于长度较长的字符串可能会有较大的时间复杂度。因此,在实际应用中,可能需要考虑更高效的算法来解决这个问题。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)