C Check all occurrences of a letter appear before another letter

18.4k Views Asked by At

So i have a string S consisting of N letters 'a' or 'b'. This should return 1 if all occurrences of A are before all occurrences of b and return 0 otherwise.

B does not need to occur in S and A does not need to occur in S

For example

S='aabbb' returns 1 
S = 'ba' returns 0
S = 'aaa' returns 1
S= 'b' returns 1

So my approach was to use a for loop on the string and check if b occurs before a or not like so:

char newstr[10] = "aabbba"; //should return 0


int len = strlen(newstr);

for (int i = 0; i < len+1; i++) {
    printf("%c", newstr[i]);
    if (newstr[i] < 'b') {
        printf("1");
    }
    else {
        printf("0");
    }

}

Output is a1a1b0b0b0a1 1 So..it is partially detecting if a is before b but not to its fully correct manner.

2

There are 2 best solutions below

2
On BEST ANSWER

Your code is simply detecting a without checking the relationship with b.

The condition "This should return 1 if all occurrences of A are before all occurrences of b and return 0 otherwise." can be said as "This should return 0 if some occurrences of A are after some occurrences of b and return 1 otherwise.".

An example implementation of this is:

char newstr[10] = "aabbba";

int b_found = 0;
int result = 1;
for (int i = 0; newstr[i] != '\0'; i++) {
    if (newstr[i] == 'b') {
        b_found = 1;
    } else if(b_found && newstr[i] == 'a') {
        /* 'a' is found after 'b' */
        result = 0;
    }
}
printf("%d", result);
0
On

i have a string S consisting of N letters 'a' or 'b'

should return 1 if all occurrences of A are before all occurrences of b and return 0 otherwise.

So string is not allowed to have a sequence ba inside. So just:

if (strstr(newstr, "ba") == NULL) { printf("1\n"); } else { printf("0\n"); }

or just:

printf("%d\n", !strstr(newstr, "ba"));