L1-064 估值一亿的AI核心代码 (20 分)
以上图片来自新浪微博。
本题要求你实现一个稍微更值钱一点的 AI 英文问答程序,规则是:
- 无论用户说什么,首先把对方说的话在一行中原样打印出来;
- 消除原文中多余空格:把相邻单词间的多个空格换成 1 个空格,把行首尾的空格全部删掉,把标点符号前面的空格删掉;
- 把原文中所有大写英文字母变成小写,除了
I
; - 把原文中所有独立的
can you
、could you
对应地换成I can
、I could
—— 这里“独立”是指被空格或标点符号分隔开的单词; - 把原文中所有独立的
I
和me
换成you
; - 把原文中所有的问号
?
换成惊叹号!
; - 在一行中输出替换后的句子作为 AI 的回答。
输入格式:
输入首先在第一行给出不超过 10 的正整数 N,随后 N 行,每行给出一句不超过 1000 个字符的、以回车结尾的用户的对话,对话为非空字符串,仅包括字母、数字、空格、可见的半角标点符号。
输出格式:
按题面要求输出,每个 AI 的回答前要加上 AI:
和一个空格。
输入样例:
6
Hello ?
Good to chat with you
can you speak Chinese?
Really?
Could you show me 5
What Is this prime? I,don 't know
输出样例:
Hello ?
AI: hello!
Good to chat with you
AI: good to chat with you
can you speak Chinese?
AI: I can speak chinese!
Really?
AI: really!
Could you show me 5
AI: I could show you 5
What Is this prime? I,don 't know
AI: what Is this prime! you,don't know
题目分析:主要是String STL函数的运用:
string.erase(); string.replace(); string.find()
解题思路:
- 输入:由于题目偏向于单词输入,可以使用
istringstream
进行按空格分割,但由于需求1,要求原样打印输入的字符串,故改用getline(cin, str)
。转载:c++按空格分割string的两种方法,C++ while(cin>>a) cin输入直到回车结束 - 由于需求4和需求5相互冲突,可以先将
can you
、could you
转换为A can
、A could
(因为之前已经将大写字母转换为小写字母,所以不用担心会出现输入字符串中的A
变为I
),最后处理?
时一起处理A
。
函数使用(转载):
- string.erase():c++ string的erase删除方法
- string.replace():C++ replace() 函数用法
- string.find(): String find函数用法
AC代码:
#include <bits/stdc++.h>
using namespace std;
// 全局变量,便于函数运用
string str;
// 判断是否为标点字符(可见的半角标点符号)
bool check(char c) {
if (c >= 'a' && c <= 'z') return false;
if (c >= 'A' && c <= 'Z') return false;
if (c >= '0' && c <= '9') return false;
return true;;
}
// 将str中特定字串target,替换为value
void find_replace(string target, string value) {
int len = target.size();
for (int i = 0; str.find(target, i) != str.npos ; ++i) {
i = str.find(target, i);
// 或者将for循环中的判断语句改成
// if (i == -1) break;
if ((i == 0 || check(str[i-1])) && (i == str.size() - len || check(str[i + len])))
str.replace(i, len, value);
}
}
int main(void) {
int t; cin >> t;
getchar();
while (t--) {
getline(cin, str);
// 1.打印原字符串
cout << str << endl;
// 2.处理空格
// 处理句首句尾空格(因为两头空格可能不止一个,所以采用循环方式擦除)
int k;
for (k = 0; str[k] == ' '; ++k);
str.erase(0, k);
for (k = str.size() - 1; str[k] == ' '; --k);
str.erase(k + 1, str.size() - k - 1);
// 处理中间多余空格
for (int i = 0; i < str.size(); ++i) {
if (str[i] == ' ') {
int j = i;
int cnt = 0;
while (str[++j] == ' ') cnt++;
str.erase(i, cnt);
}
// 处理标点符号前面的空格
if (check(str[i])) { // 判断是否为标点字符(可见的半角标点符号)
int j = i;
int cnt = 0;
while (str[--j] == ' ') cnt++;
str.erase(j + 1, cnt);
}
}
// 3.大写转小写
for (int i = 0; i < str.size(); ++i) {
if (str[i] >= 'A' && str[i] <= 'Z' && str[i] != 'I')
str[i] += 32;
}
// 4.寻找特定字串,并将其替换为特定值
find_replace("can you", "A can");
find_replace("could you", "A could");
// 5
find_replace("I", "you");
find_replace("me", "you");
// 6.将?和'A'统一处理
for (int i = 0; i < str.size(); ++i) {
if (str[i] == '?') str.replace(i, 1, "!");
if (str[i] == 'A') str[i] = 'I';
}
// 7.输出结果
cout << "AI: ";
cout << str << endl;
}
return 0;
}
思路参考(转载):PTA 估值一亿的AI核心代码