给定大小为ns的字符串s,其中仅包含'x'和'y'

问题描述 投票:0回答:1

给出大小为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;
    }
c++ substring
1个回答
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 } }

然后只打印两个计数器的和。

© www.soinside.com 2019 - 2024. All rights reserved.