P11034 题解
1. 题目大意
输入两个字符串,。检查,转小写后是否包含rioi字串:
-
- 若两者都有
rioi子串,则输出Either is ok! - 若只有一个字符串拥有
rioi子串,则输出那个字符串,再输出for sure! - 若两个字符串都没有
rioi子串,则输出Try again!
- 若两者都有
2. 代码实现
AC 代码(C++)
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string s, t;
bool is_shan(string str) { // 判断字符串是不是“闪”的
for (char& ch : str) {
ch = tolower(ch);
} // 转小写
if (str.find("rioi") != string::npos) { // 判断是否有rioi子串
return true;
}
return false;
}
int main() {
cin >> s >> t;
if (is_shan(s)) {
if (is_shan(t)) { // s 和 t 满足
cout << "Either is ok!";
} else { // 仅 s 满足
cout << s << " for sure!";
}
} else {
if (is_shan(t)) { // 仅 t 满足
cout << t << " for sure!";
} else { // 没有字符串满足
cout << "Try again!";
}
}
return 0;
}3. 这就完了……吗?
我们可以简化一下代码,用一个变量answer存储所有的可能,answer为2 * is_shan(s) + is_shan(t):
的情况(true 或 false) | 的情况 (true 或 false) | answer |
|---|---|---|
false | false | |
false | true | |
true | false | |
true | true |
这样的话,我们的answer和, 一一对应了!
AC 代码 Pro(C++)
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
string s, t;
bool is_shan(string str) { // 判断字符串是不是“闪”的
for (char& ch : str) {
ch = tolower(ch);
} // 转小写
if (str.find("rioi") != string::npos) { // 判断是否有rioi子串
return true;
}
return false;
}
int main() {
cin >> s >> t;
int answer = 2 * is_shan(s) + is_shan(t);
switch (answer) {
case 0: cout << "Try again!"; break; // 没有一个满足
case 1: cout << t << " for sure!"; break; // t 满足
case 2: cout << s << " for sure!"; break; // s 满足
case 3: cout << "Either is ok!"; break; // t, s 都满足
}
return 0;
}AC 代码 Pro(Python)
str1, str2 = input(), input()
answer = (str1.lower().count("rioi") != 0) * 2 +(str2.lower().count("rioi") != 0)
match answer: # Python 3.10+ 的模式匹配match,相当于switch
case 0:
print("Try again!")
case 1:
print(f"{str2} for sure!")
case 2:
print(f"{str1} for sure!")
case 3:
print("Either is ok!")
# 以下是不用match的版本 ↓
"""
if answer == 0:
print("Try again!")
elif answer == 1:
print(f"{str2} for sure!")
elif answer == 2:
print(f"{str1} for sure!")
elif answer == 3:
print("Either is ok!")
"""Q & A
这里会处理大家可能遇到的问题,如果没有你次想问的别来打我
- Q1: 为什么选取的是
answer为2 * is_shan(s) + is_shan(t)? - A1:其实把所有情况一一对应就可以了,
a * is_shan(s) + b * is_shan(t)()其实都是可以的。 - Q2:C++部分有没有其他方法转小写字母?
- A2:
std::fransform,std::ranges::to_lower(std=-stdc++20及以上)也都可以。 - Q3:为什么你能知道这道题要转小写再去寻找
rioi? - A3:因为题目里说了,
Rioi,rIOI,RiOi等都是可以匹配的,所以大小写要统一,其实转大写也不是不行。读者可以自行实现。