C. Rudolf and the Ugly String
Rudolf has a string ss of length nn. Rudolf considers the string s to be ugly if it contains the substring† "pie" or the substring "map", otherwise the string s will be considered beautiful.
For example, "ppiee", "mmap", "dfpiefghmap" are ugly strings, while "mathp", "ppiiee" are beautiful strings.
Rudolf wants to shorten the string s by removing some characters to make it beautiful.
The main character doesn't like to strain, so he asks you to make the string beautiful by removing the minimum number of characters. He can remove characters from any positions in the string (not just from the beginning or end of the string).
String a is a substring of b if there exists a consecutive segment of characters in string b equal to a.
Input
The first line contains a single integer t (1≤t≤104) — the number of test cases. The descriptions of the test cases follow.
The first line of each test case contains a single integer n(1≤n≤106) — the length of the string s.
The next line of each test case contains the string s of length n. The string ss consists of lowercase Latin letters.
The sum of nn over all test cases does not exceed 106.
Output
For each test case, output a single integer — the minimum number of characters that need to be deleted to make the string s beautiful. If the string is initially beautiful, then output 0.
题意:
对于给定字符串s,你可以对其中的任意位置进行删除,使的s的子串中不含有"map",和"pie", 对于map和pie ,你只需要删除一个位置即可改变,但请尤其注意"mapie", 其既含有“map”,有含有“pie”,因此,相当于ans加了两次,在map时加了一次,在pie时加了一次,所以在遇到mapie时要ans--;
substr 函数:
substr
是 C++ 标准库中std::string
类的成员函数,用于从一个字符串中提取子串。cpp
std::string substr(size_t pos = 0, size_t count = npos) const;
参数说明
pos
:子串的起始位置,即从原始字符串中的哪个索引开始提取,默认为 0。count
:子串的长度,即要提取的字符个数。默认值npos
表示提取从起始位置pos
到字符串末尾的所有字符。返回值
- 返回一个
std::string
对象,包含从原始字符串中提取的子串。
代码实现:
#include<bits/stdc++.h>
using namespace std;
void solve()
{
int n; cin>>n;
string s; cin>>s;
int ans=0;
for(int i=0;i<n;i++)
{
if(i+3<=n && s.substr(i,3)=="map")
{
ans++;
}
if(i+3<=n && s.substr(i,3)=="pie")
{
ans++;
}
if(i+5<=n && s.substr(i,5)=="mapie")
{
ans--;
}
}
cout<<ans<<endl;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin>>t;
while(t--)
{
solve();
}
return 0;
}