以上圖片來自新浪微博。
本題要求你實現一個稍微更值錢一點的 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
思路:
這道題浪費我一堆時間最后還沒寫出來,我佛了,后面補了這道題,
我的寫法是在分隔符號之前插入空格,處理之后再根據空格作為獨立條件導入vector開的string數組,再處理“can you” or“could you”的問題,最后輸出要注意,分隔符號前不能輸出空格,判斷一遍再輸出就好了......
1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<cmath>
5 #include<algorithm>
6 #include<map>
7 #include<set>
8 #include<vector>
9 using namespace std; 10 #define ll long long
11 #define dd cout<<endl
12 const int inf=99999999; 13 const int mod=1e9+7; 14 const int maxn=1e6+7; 15 string str; 16 vector<string>v; 17 int main() 18 { 19 int T; 20 cin>>T; 21 getchar(); 22 while(T--) 23 { 24 getline(cin,str); 25 cout<<str<<endl<<"AI: "; 26 for(int i=0;i<str.size();i++) 27 { 28 if(str[i]>='A'&&str[i]<='Z')//字母
29 { 30 if(str[i]!='I')//'I'不變
31 str[i]=str[i]-'A'+'a'; 32 } 33 else if((str[i]>='0'&&str[i]<='9')||(str[i]>='a'&&str[i]<='z'))//數字和小寫字母跳過
34 continue; 35 else if(str[i]!=' ')//只剩下分割符號,除去空格
36 { 37 str.insert(i," ");//插入空格實現獨立
38 i++; 39 } 40 if(str[i]=='?')//'?'變
41 str[i]='!'; 42 } 43 v.clear(); 44 string temp=""; 45 //以空格為分隔將字符串拆分讀入string數組
46 for(int i=0;i<str.size();i++) 47 { 48 if(str[i]!=' ') 49 temp+=str[i]; 50 else if(str[i]==' ') 51 { 52 if(temp!="") 53 { 54 v.push_back(temp); 55 temp=""; 56 } 57 } 58 } 59 //處理剩余字符串
60 if(temp!="") 61 { 62 v.push_back(temp); 63 temp=""; 64 } 65 for(int i=0;i<v.size();i++) 66 { 67 if(v[i]=="I"||v[i]=="me") 68 v[i]="you"; 69 else if(v[i]=="you") 70 { 71 if(i<1||v[i-1].size()==1) 72 continue; 73 if(v[i-1]=="can"||v[i-1]=="could") 74 { 75 v[i]=v[i-1];// 小細節 "can" or "could"
76 v[i-1]="I"; 77 } 78 } 79 } 80 for(int i=0;i<v.size();i++) 81 { 82 cout<<v[i]; 83 if(i==v.size()-1)//防止越界導致段錯誤
84 continue; 85 if((v[i+1][0]>='a'&&v[i+1][0]<='z')||(v[i+1][0]>='0'&&v[i+1][0]<='9')||(v[i+1][0]=='I'))//后面字符串不為分隔符號
86 cout<<" "; 87 } 88 cout<<endl; 89 } 90 return 0; 91 }