L1-064 估值一亿的AI核心代码【模拟】
L1-064 估值一亿的AI核心代码
https://pintia.cn/problem-sets/994805046380707840/problems/1111914599412858885
题目
以上图片来自新浪微博。
本题要求你实现一个稍微更值钱一点的 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
分析
模拟。主要思路是根据空格和分隔符将字符串分割为独立的字符串。
C++程序
#include<iostream>
#include<ctype.h>
#include<vector>
#include<string>
using namespace std;
vector<string>v;//存放结果
int main()
{
int n;
string s;
cin>>n;
getchar();
while(n--)
{
getline(cin,s);
cout<<s<<endl<<"AI: ";//先输出原文和"AI: "
int len=s.length();
for(int i=0;i<len;i++)//将'?'改为'!' 所有大写英文字母变成小写,除了 I;
{
if(s[i]=='?')
s[i]='!';
else if(isupper(s[i])&&s[i]!='I')
s[i]=tolower(s[i]);
}
v.clear();//将由空格和分隔符分割后的字符串顺序放到v中
for(int i=0;i<len;)
{
string tmp="";//此次获得的字符串
if(isalpha(s[i]))//如果开始字符是字母,说明要读取一个字母串
{
while(i<len&&isalpha(s[i])) tmp+=s[i++];
}
else if(isdigit(s[i]))//如果开始字符是数字,说明要读取一个数字串
{
while(i<len&&isdigit(s[i])) tmp+=s[i++];
}
else if(s[i]==' ')//如果开始字符是控空格,跳过其后的连续空格
{
tmp=" ";
while(i<len&&s[i]==' ') i++;
}
else//否则是分隔符
{
tmp+=s[i];
i++;
//如果分隔符前面是空格,就删除前面的空格
if(v.size()>0&&v.back()==" ") v.pop_back();
}
if(tmp==" "&&(v.empty()||i==len)) continue;//去掉首尾的空格
v.push_back(tmp);
}
for(int i=0;i<v.size();i++)
if(v[i]=="I"||v[i]=="me")//如果是 I、me均换成 you
v[i]="you";
else if(v[i]=="you")//如果是 you
{
//如果i<2或者v[i-1]不是分隔符或空格就跳过
if(i<2||!(v[i-1].length()==1&&(!isalnum(v[i-1][0])))) continue;
if(v[i-2]=="can")
v[i-2]="I",v[i]="can";
else if(v[i-2]=="could")
v[i-2]="I",v[i]="could";
}
//输出
for(int i=0;i<v.size();i++)
cout<<v[i];
cout<<endl;
}
return 0;
}