<分区>
我正在尝试解决一个问题,我需要在主字符串中找到第 i 个“字符串”的位置。
例如。 : bearacbear,我需要找到第二个“熊”的位置(不使用 substr)
这是我目前的解决方案(包含 substr 的错误,这就是为什么我问是否有更好的方法)
#include <iostream>
#include <algorithm>
#include <iterator>
#include <assert.h>
#include <cmath>
#include <sstream>
#include <iomanip>
#include <vector>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <ctime>
#define ull unsigned long long // for n^12
#define ll long long
#define ld long double
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
using namespace std;
int main()
{
std::ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
string str;
cin >> str;
ll ans = 0, len;
for (int i = 0; i < str.size() - 2; i++)
{
string s = str.substr(i, str.size());
len = s.size();
int pos = s.find("bear") + str.size() - s.size();
if (s.find("bear") != string::npos)
ans += (len - pos - 3);
}
cout << ans;
system("pause");
}