文章

17

粉丝

177

获赞

42

访问

144.2k

头像

直接使用字符串做递归判断,需要计算大于根的字串和小于根的字串

P1317 浙江大学机试题
发布于 2021年9月
阅读数 8.9k

#include<iostream>
using namespace std;

string larger_than_root(string s){  //计算比根大的子串
    int start_pos = 0;
    while(start_pos < s.length()){
        if(s[start_pos] > s[0]) break;
        else start_pos++;
    }
    int end_pos = start_pos + 1;
    while(end_pos < s.length()){
        if(s[end_pos] < s[0]) break;
        else end_pos++;
    }
    return s.substr(start_pos, end_pos - start_pos);
}
string lower_than_root(string s){  //计算比根小的字串
    int start_pos = 0;
    while(start_pos < s.length()){
        if(s[start_pos] < s[0]) break;
        else start_pos++;
    }
    int end_pos = start_pos + 1;
    while(end_pos < s.length()){
        if(s[end_pos] > s[0]) break;
        else end_pos++;
    }
    return s.substr(start_pos, end_pos - start_pos);

}
bool is_same_search_tree(string s1,string s2){
    if(s1.length() != s2.length()) return false; //如果长度都不相等肯定不是
    else if(s1.length() == 0){ //都是长度为零,肯定是
        return true;
    }
    else{ // 否则寻找两个字符串的大于根的子串和小于根的子串,判断根和两侧子树是否相等
        string lower_than_root_s1 = lower_than_root(s1);
        string higher_than_root_s1 = larger_than_root(s1);
        string lower_than_root_s2 = lower_than_root(s2);
        string higher_than_root_s2 = larger_than_root(s2);
        return s1[0] == s2[0] && is_same_search_tree(lower_than_root_s1, lower_than_root_s2) && is_same_search_tree(higher_than_root_s1, higher_than_root_s2);
    }

}
int main()
{
    int n;
    string mod, check;
    while(cin >> n && n){
        cin >> mod;
        while(n--){
            cin >> check;
            cout << (is_same_search_tree(mod, check)? "YES":"NO") << endl;
        }
    }

}


 



登录后发布评论

1 条评论
xiao菜
2025年3月12日 11:20

思路很好,就是那个提取左右子树的函数写的有点小问题,作者那么写只能提取出后面连续一段的,如果断开的,就会没处理到,比如3452168

第一次提取3的右子树只能提取到45而68没提取到

若要正确处理所有比根大的字符,应修改 larger_than_root 和 lower_than_root 函数,直接遍历所有字符,而非仅提取连续的一段。

string larger_than_root(string s) {

string res;

for (int i = 1; i < s.length(); ++i) {

if (s[i] > s[0])

{ res += s[i]; }

} return res;

}

string lower_than_root(string s) {

string res;

for (int i = 1; i < s.length(); ++i) {

if (s[i] < s[0]) {

res += s[i]; }

}

return res;

}

赞(0)
回复给: