团体程序设计天梯赛 L1-064 估值一亿的AI核心代码 题解

发布时间 2023-04-21 18:55:08作者: 1v7w

思路

L1-064 估值一亿的AI核心代码

题意有一点不太清晰的,就是原文中的'I',无论是否是单独的,都不能变为小写。如果是单独的'I'再被转化为'you'。

这种模拟题就需要每个的分分清清楚楚的,不要都揉到一块儿,容易写错。具体还有些需要注意的在代码里注释着了。

代码

#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <cstring>

#define fi first
#define se second

using namespace std;
using ll = long long;
using pii = pair<int, int>;

const double eps = 1e-4;

// 把字符串s的第pos个位置开始,长len的子串,替换为s1
string replace_str(string &s, int pos, int len, string s1) {
    string t1 = s.substr(0, pos), t2 = s.substr(pos+len, (int)s.size()-(pos+len));
    return t1 + s1 + t2;
}

// 判断s[pos]是不是字母
bool check_is_alpha(string &s, int pos) {
    if(pos < 0 || pos >= (int)s.size()) return false;
    char c = s[pos];
    if((c>='a' && c<='z') || (c>='A' && c<='Z')) return true;
    return false;
}

void solve() {
    string s;
    getline(cin, s);
    cout << s << endl;
    
    // 删除空格
    while(s.back() == ' ') s.pop_back();    // 删除行尾空格
    for(int i=0; i<(int)s.size(); i++) {    // 删除超过1个的空格 and 行首空格
        if(s[i] == ' ') {
            if(i == 0) {
                s.erase(0, 1);
                i--;
            }
            else {
                int j=i;
                while(j<(int)s.size() && s[j] == ' ') j++;
                s.erase(i, j-i-1);
            }
        }
    }
    for(int i=0; i<(int)s.size()-1; i++) {    // 删除符号前的空格
        if(s[i] == ' ' && (s[i + 1]<'0'|| s[i + 1]> '9') && (s[i + 1]<'A'|| s[i + 1]>'Z') && (s[i + 1]<'a' || s[i + 1]>'z')) {
            s.erase(i, 1);
            i--;
        }
    }

    // 所有大写字母都变成小写
    for(int i=0; i<(int)s.size(); i++) {
        if(s[i] >= 'A' && s[i] <= 'Z' && s[i] != 'I') s[i] += 'a' - 'A';
    }

    // 把原文中所有独立的 can you、could you 对应地换成 I can、I could
    // 把原文中所有独立的 I 和 me 换成 you;
    for(int i=0; i<(int)s.size(); i++) {
        // 如果s[i]前面不是字母
        if(!check_is_alpha(s, i-1)) {
            // 如果从i开始的子串最少长度为7 && 长度为7的子串的下一个字符不是字母 && 这个长度为7的子串是"can you"
            if(i+7 <= (int)s.size() && !check_is_alpha(s, i+7) && s.substr(i, 7) == "can you") 
                s = replace_str(s, i, 7, "I can");
            else if(i+9 <= (int)s.size() && !check_is_alpha(s, i+9) && s.substr(i, 9) == "could you")
                s = replace_str(s, i, 9, "I could");
            else if(i+1 <= (int)s.size() && !check_is_alpha(s, i+1) && s.substr(i, 1) == "I") 
                s = replace_str(s, i, 1, "you");
            else if(i+2 <= (int)s.size() && !check_is_alpha(s, i+2) && s.substr(i, 2) == "me") 
                s = replace_str(s, i, 2, "you");
        }
    }

    // 把?->!
    for(auto &c: s) if(c == '?') c = '!';

    s = "AI: " + s;
    cout << s << endl;
}

int main() {
    // multiple case
    int t; scanf("%d", &t);
    getchar();
    while(t--) {
        solve(); 
    }

    // single case
    // solve();

    return 0;
}