第六天练习(学习PTA题目的标准答案以及复习string函数知识)

#include <iostream>
#include <string>
using namespace std;

bool check(string s) {
    int p_pos = -1, t_pos = -1;
    int p_count = 0, t_count = 0;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == 'P') {
            if (p_count > 0) return false; // P重复出现
            p_pos = i;
            p_count++;
        } else if (s[i] == 'T') {
            if (t_count > 0) return false; // T重复出现
            t_pos = i;
            t_count++;
        } else if (s[i] != 'A') {
            return false; // 其他字符出现
        }
    }
    if (p_pos == -1 || t_pos == -1 || p_pos >= t_pos - 1) {
        return false; // 没有P或T或者它们的相对位置不正确
    }
    int a_count_before_p = p_pos;
    int a_count_between_p_t = t_pos - p_pos - 1;
    int a_count_after_t = s.size() - t_pos - 1;
    if (a_count_between_p_t == 0) {
        return a_count_before_p == a_count_after_t; // PAT中A的数量相等
    } else if (a_count_between_p_t > 0) {
        if (a_count_before_p * a_count_between_p_t == a_count_after_t) {
            return true; // 满足形如 xPATx 的条件
        } else {
            int k = a_count_after_t % a_count_between_p_t;
            if (k == 0 && a_count_before_p * a_count_after_t / a_count_between_p_t == a_count_before_p + a_count_after_t) {
                return true; // 满足形如 aPbATca 的条件
            }
        }
    }
    return false;
}

int main() {
    int n;
    cin >> n;
    string s;
    for (int i = 0; i < n; i++) {
        cin >> s;
        if (check(s)) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
    }
    return 0;
}

#include <iostream>
#include <string>
using namespace std;

int main() {
// 字符串拼接
string s1 = "Hello, ";
string s2 = "world!";
string s3 = s1 + s2;
cout << s3 << endl; // 输出:Hello, world!

// 字符串查找
string s4 = "abcdefg";
if (s4.find("cd") != string::npos) {
cout << "Found!" << endl; // 输出:Found!
} else {
cout << "Not found." << endl;
}

// 字符串替换
string s5 = "hello world";
s5.replace(6, 5, "there");
cout << s5 << endl; // 输出:hello there

// 字符串截取
string s6 = "abcdefg";
string s7 = s6.substr(2, 3);
cout << s7 << endl; // 输出:cde

// 字符串转整数
string s8 = "123";
int x = stoi(s8);
cout << x << endl; // 输出:123

// 整数转字符串
int y = 456;
string s9 = to_string(y);
cout << s9 << endl; // 输出:456

return 0;
}

posted @ 2023-04-19 20:26  KuanDong24  阅读(19)  评论(0编辑  收藏  举报