Search code examples
c++stringif-statementcharimplementation

CodeForces stones on table, code cannot pass one test case I cannot understand why


This is the question - There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.

Input - The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table.

The next line contains string s, which represents the colors of the stones. We'll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals "R", if the i-th stone is red, "G", if it's green and "B", if it's blue.

Output - The answer

My code - ```

int main(){
    string s;
    int q,a,b,c;
    cin >> q;
    cin >> s;
    a = s.length();
    for(int i=0;i<q;i++){
            if((s[i]=='R'&&s[i+1]=='R')||(s[i]=='G'&&s[i+1]=='G')||(s[i]=='B'&&s[i+1]=='B')){
                s.erase(i+1,i+1);
            }
        }
    b = s.length();
    c = a - b;
    if((s[0]=='R'&&s[1]=='R')||(s[0]=='G'&&s[1]=='G')||(s[0]=='B'&&s[1]=='B')){
        cout << c+1;
       }else{ cout << c;
       }
}

When the input is "4 RBBR", the output shows 2 instead of 1, i'm not understanding why its doing that, could someone help me. Here are some other test cases which my code passes - "3 RRG" "5 RRRRR"


Solution

  • int main()
    {
        string s;
        size_t q, a, c;
        cin >> q;
        cin >> s;
        a = s.length();
    
        // You may not use q here, because you are modifying the string length, so when the
        // loop enters the next iteration, q is no longer valid.
        // Since you are comparing it with the next item, you must reduce the count by 1, otherwise you read out of bounds.
        // It's also wrong to use q here, because the user can enter an invalid length. i.E. "5 RR".
        for (size_t i = 0; i < s.length()-1; i++)
        {
            if (s[i] == s[i + 1])
            {
                // Here 'i' may not be increased, because the next character can also be a neighbor now
                s.erase(i + 1, 1);
                i--;
            }
        }
    
        c = a - s.length();
        cout << c;
    
        return 0;
    }