PCM_Dilemma

Plz tell me this approach is correct or not

#include<iostream>

#include<string>

using namespace std;

int main()

{

    int t;

    cin>>t;

    while(t--)

    {

        string s;

        cin>>s;

        int len = s.length();

        bool res=false;

        for(int i=0;i<len;i++)

        {

            if((s[i] == 'P' && s[i+1] == 'C' && s[i+2] == 'M') || (s[i] == 'C' && s[i+1] == 'P' && s[i+2] == 'M') ||

            (s[i] == 'M' && s[i+1] == 'C' && s[i+2] == 'P') || (s[i] == 'P' && s[i+1] == 'M' && s[i+2] == 'C') || (s[i] == 'C' && s[i+1] == 'M' && s[i+2] == 'P') || (s[i] == 'M' && s[i+1] == 'P' && s[i+2] == 'C') )

             {

                 res = true;

             }

        }

        if(res)

        {

            cout<<"YES"<<endl;

        }

        else

        {

            cout<<"NO"<<endl;

        }

    }

    return 0;

}

The length of the input string is fixed at 3. In your for-loop, you are checking for s[i+1] and s[i+2], which will go out of the string length.

1 Like

Just sort the string and check if it’s equal to CMP

#include "bits/stdc++.h"
using namespace std ;
int main(){	
  int TC ;
  cin>>TC ;
  while(TC--){
    string s ;cin>>s;
    sort(s.begin(),s.end()) ;
    cout<<(s=="CMP"?"YES\n":"NO\n") ;
  }
}

2 Likes

you can also use the ascii value for the characters…if sum of all characters’ ascii value in the string was equal to the sum of the ascii value of P, C and M, Then the string is accepted. To do so, just cast the characters into int. (Note that the sum of ascii values of PCM is 224.)

2 Likes

For this we have to convert string to char array right ? or we directly convert string into their ascii value

You can directly loop through the string (character by character) and add the ascii value.

1 Like

Thanks bro