#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;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:顺序表储存空间时一次性分配的,链表的是多次分配的
(注: 存储密度 = 结点值域所占存储量/结点结构所占存储总量)
顺序表存储密度 = 1
链表存储密度 < 1