PAT : 团体程序设计天梯赛-练习集 L1-064 估值一亿的AI核心代码
这次天梯赛L1就卡住的题…情况比较复杂的模拟
每日反思自己怎么这么菜...回家调了快一上午才做对。
C++11:
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool check(const string &a, string::size_type pos, int cstrlen)
{
bool ok1{false}, ok2{false};
if ((pos == 0) || a[pos - 1] == ' ' || ispunct(a[pos - 1]))
ok1 = true;
if ((pos + cstrlen - 1 == a.size() - 1) || a[pos + cstrlen] == ' ' || ispunct(a[pos + cstrlen]))
ok2 = true;
return ok1 & ok2;
}
void stringreplace(string &a)
{
int cstrlen[] = {7, 9, 1, 2};
int rstrlen[] = {5, 7, 3, 3};
char aimstr[][10] = {"can you", "could you", "I", "me"};
char restr[][10] = {"I can", "I could", "you", "you"};
string::size_type pos = 0;
while (pos != a.size())
{
int i;
for (i = 0; i != 4; ++i)
{
if (a.compare(pos, cstrlen[i], aimstr[i]) == 0)
if (check(a, pos, cstrlen[i]))
{
a.replace(pos, cstrlen[i], restr[i]);
pos += rstrlen[i];
break;
}
}
if (i == 4)
++pos;
}
}
int main(int argc, char **argv)
{
int cnt;
cin >> cnt;
cin.get();
while (cnt--)
{
string str;
getline(cin, str);
cout << str << endl;
cout << "AI: ";
vector<string::size_type> spaceindex;
string::size_type pos = 0;
string::size_type l = 0, r = str.size();
while (pos != str.size() && str[pos] == ' ')
++pos;
l = pos;
pos = str.size() - 1;
while (pos >= l && str[pos] == ' ')
--pos;
r = pos + 1;
str = str.substr(l, r - l);
pos = 0;
while ((pos = str.find(' ', pos)) != string::npos)
{
if ((str[pos + 1] == ' ') || (ispunct(str[pos + 1])))
spaceindex.push_back(pos);
++pos;
}
vector<int>::size_type ind = 0;
string::size_type j = 0;
for (string::size_type i = 0; i != str.size(); ++i)
{
if (ind != spaceindex.size() && i == spaceindex[ind])
++ind;
else
str[j++] = str[i];
}
str.erase(j);
for (auto &i : str)
{
if (isupper(i) && i != 'I')
i = tolower(i);
if (i == '?')
i = '!';
}
stringreplace(str);
cout << str << endl;
}
return EXIT_SUCCESS;
}
细节很多,我的顺序是
1. 处理行首尾空格。
2. 处理单词间和标点符号前的空格。
3. 除' I '以外的大写字母换为小写 + ' ? '转' ! ' 。
4. 从头往后遍历,循环比较四个单词,发现当前位置存在四个单词之一就判断它的独立性;
如果该单词独立,那么替换成目标单词,然后遍历的下标加上目标单词的长度;
如果没发现或者单词不独立,那么遍历的下标加 1 。
输出!