请问我哪儿错了,有空请看一下

img


#include
#include
#include
using namespace std;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n,cot=0,cot2=0;
    cin>>n;
    string s;
    cin>>s;
    for(int i=0;isize();i++)
    {
        if(s.find("swust")!=-1) 
        {
            cot++;
        int a = s.find("swust");
        s.erase(a,a+4);
        }
    }
    cout<

你的代码中有一个问题。在你的循环中,你使用了s.find("swust")来查找子串"swust",但是你没有更新查找的起始位置。这意味着,如果字符串中包含多个"swust"子串,你的代码只会找到第一个。

此外,你使用了s.erase(a,a+4)来删除找到的子串。但是s.erase(a,a+4)并不会删除从位置a开始的5个字符,而是删除从位置a开始的4个字符。正确的写法应该是s.erase(a,5)。
下面是修改后的代码:

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n,cot=0,cot2=0;
    cin>>n;
    string s;
    cin>>s;
    size_t pos = 0;
    while ((pos = s.find("swust", pos)) != string::npos) {
        cot++;
        pos += 5;
    }
    cout<<cot<<endl;
}

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, cot = 0;
    cin >> n;
    string s;
    cin >> s;
    for (int i = 0; i <= s.size() - 5; i++)  // 因为 "swust" 有 5 个字符,所以最多只能从第 s.size() - 5 个字符开始查找
    {
        if (s.substr(i, 5) == "swust")
        {
            cot++;
            i += 4;  //找到一个子串后,跳过它,直接开始查找下一个子串
        }
    }
    cout << cot << endl;
    return 0;
}

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/899120
  • 这篇博客你也可以参考下:【编程基础】堆空间与栈空间
  • 除此之外, 这篇博客: 链表的定义中的 基于空间比较 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
    • 储存的分配方式

    顺序表储存空间时一次性分配的,链表的是多次分配的

    • 存储密度

    (注: 存储密度 = 结点值域所占存储量/结点结构所占存储总量

    顺序表存储密度 = 1

    链表存储密度 < 1


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^