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

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

image-af792a1f

思路分析

代码实现

#include <bits/stdc++.h>

using namespace std;

#define endl '\n'

using ll = long long;

using ull = unsigned long long;

using PII = pair<int, int>;

using Pll = pair<ll, ll>;

int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };

const int inf = 0x3f3f3f3f;

// 去除多余空格,标点前空格也要删除

string normalize_space(const string& input) {

    stringstream ss(input);

    string word, result;

    while (ss >> word) {

        if (!result.empty()) result += " ";

        result += word;

    }

    // 删除标点前的空格

    string res2;

    for (size_t i = 0; i < result.size(); ++i) {

        if (i > 0 && ispunct(result[i]) && result[i - 1] == ' ') {

            res2.pop_back(); // 删除标点前的空格

        }

        res2 += result[i];

    }

    return res2;

}

// 判断某位置是否为独立的单词

bool is_word_boundary(const string& s, int start, int len) {

    bool left = (start == 0 || !isalnum(s[start - 1]));

    bool right = (start + len >= s.size() || !isalnum(s[start + len]));

    return left && right;

}

// 将所有大写字母转小写,除了大写的I

string to_lower_custom(const string& input) {

    string res;

    for (char c : input) {

        if (c == 'I') {

            res += 'I';

        } else if (isupper(c)) {

            res += tolower(c);

        } else {

            res += c;

        }

    }

    return res;

}

// 替换函数(匹配独立单词)

void replace_word(string& str, const string& from, const string& to) {

    size_t pos = 0;

    while ((pos = str.find(from, pos)) != string::npos) {

        if (is_word_boundary(str, pos, from.length())) {

            str.replace(pos, from.length(), to);

            pos += to.length();

        } else {

            pos += from.length();

        }

    }

}

int main() {

    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    int N;

    cin >> N;

    cin.ignore();

    for (int i = 0; i < N; ++i) {

        string line;

        getline(cin, line);

        cout << line << endl;

        // 1. 消除多余空格

        string clean = normalize_space(line);

        // 2. 转小写(保留所有的大写I)

        clean = to_lower_custom(clean);

        // 3. 替换独立的 I 和 me 为 you

        replace_word(clean, "I", "you");

        replace_word(clean, "me", "you");

        // 4. 替换 can you -> I can, could you -> I could

        replace_word(clean, "could you", "I could");

        replace_word(clean, "can you", "I can");

        // 5. 替换问号为感叹号

        for (char& c : clean) {

            if (c == '?') c = '!';

        }

        // 输出 AI 回复

        cout << "AI: " << clean << endl;

    }

    return 0;

}

同类题型

视频讲解


⬅️ L1-063 吃鱼还是吃肉 🏠 00-天梯赛 ➡️ L1-065 嫑废话上代码