1 条题解

  • 0
    @ 2026-1-30 11:16:57
    #include<bits/stdc++.h>
    using namespace std;
    
    int main() {
        string s,t;
        cin>>s>>t; // [1] 读取输入的原字符串s和待删除的子串t
        int n=s.size(),m=t.size(); // [2] 获取原字符串长度n和子串长度m
        string new_s=""; // [3] 初始化存储删除结果的字符串
        int i=0; // [4] 手动定义遍历索引,脱离for循环默认自增,避免逻辑冲突
    
        // [5] 遍历原字符串可匹配子串的区域,寻找并删除所有子串t
        while(i <= n-m){
            if(s[i]==t[0]){ // [6] 首字符预判,减少不必要的子串匹配
                string new_c="";
                for(int j=0;j<m;j++){
                    new_c+=s[i+j]; // [7] 截取从i开始、长度为m的子串
                }
                if(new_c==t){ // [8] 判断截取的子串是否与t完全匹配
                    i += m; // [9] 匹配成功,直接跳过整个子串,无自增叠加问题
                    continue;
                }
            }
            new_s+=s[i]; // [10] 不匹配时,将当前字符加入结果字符串
            i++; // [11] 未匹配,索引正常自增
        }
    
        // [12] 处理原字符串末尾无法匹配子串的剩余字符,补全结果无遗漏
        while(i < n){
            new_s += s[i];
            i++;
        }
    
        cout<<new_s; // [13] 输出删除所有子串t后的完整结果
        return 0;                  
    }
    
    • 1

    信息

    ID
    123
    时间
    1000ms
    内存
    256MiB
    难度
    2
    标签
    递交数
    4
    已通过
    1
    上传者