输出B在 A 中出现的次数

img

img

#include 
#include
using namespace std;
int main()
{
    int n, i, l, j,g;
    cin >> n;
    string a[6];
    string b[6];
    bool t;
    for (i = 1; i <= n; i++)
    {
        cin >> a[i];
        cin >> b[i];

    }
    for (i = 1; i <= n; i++)
    {
        l = a[i].size();
        t = true;
        int num = 0;
        for (j = 0; j < l; j++)
        {
            string m = a[i].substr(j, 1);
            if ((m >= "0") && (m <= "9"))
            {
                cout << "-1" << endl;
                t = false;
                break;


            }
        }
        if (t == false)
            continue;


        for (j = 0; j < l; j++)
        {
            g = b[i].size();
            
            string d = a[i].substr(j, g);
            if (d == b[i] && t == true)
                num = num + 1;
        }




        cout << num << endl;


    }

    return 0;

}


``` 用代码块功能插入代码,请勿粘贴截图 

###### 时间超限

###### 我的解答思路和尝试过的方法 

###### 我想要达到的结
为什么会时间超限,如何解决

你的有点麻烦,灵活使用string类提供的方法可以很简单地完成本题。我给你写了个版本,供你参考。如果对你有帮助,请采纳。

#include <iostream>

using namespace std;


int main() {
    int n;
    cin >> n;
    int count = 0;
    string a, b;
    for (int i = 0; i < n; i++) {
        cin >> a >> b;
        if (a.find_first_of("0123456789") != std::string::npos) {
            cout << -1 << endl;
            continue;
        }
        for (size_t j = 0; (j = a.find(b, j)) != string::npos; count++, j++);
        cout << count << endl;
    }
    return 0;
}