给出大小为n的字符串s。我们必须计算“ xy”或“ yx”对的数量。
test case:
xyxxy
xy
yy
output:
2
1
0
我解决了大部分问题,但被困在字符串为'xxyy'的测试用例中。我不知道解决此问题的最佳方法“建议我”。我已经通过仅使用if-else解决了这个问题,但无法进入交流中心。
我的代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
int cntx=0,cnty=0;
for(unsigned int i=0;i<s.size();++i){
if(s[i]=='x') cntx++;
if(s[i]=='y') cnty++;
}
if(cntx>cnty){
cout<<cntx-(cntx-cnty)<<"\n";
}
else if(cnty>cntx){
cout<<cnty-(cnty-cntx)<<"\n";
}
else if(cntx==cnty){
cout<<cntx<<"\n";
}
else{
cout<<0<<"\n";
}
}
return 0;
}
// Use length of string minus one, because we don't need to
// check the very last character (it can never meet our conditions)
// It also means we don't have to do bounds-checking inside the loop
for (unsigned i = 0; i < s.length() - 1; ++i)
{
if (s[i] == 'x' && s[i + 1] == 'y')
{
++xy_count;
++i; // Together with the loop increase will be equivalent to i += 2
}
else if (s[i] == 'y' && s[i + 1] == 'x')
{
++yx_count;
++i; // Together with the loop increase will be equivalent to i += 2
}
}
然后只打印两个计数器的和。