Check if All A's Appears Before All B's

We will approach this problem by first finding the index of the last occurrence of ‘a’ and the first occurrence of ‘b’. If the last occurrence of ‘a’ is before the first occurrence of ‘b’, then all ‘a’s are before all ‘b’s, and we return True. Otherwise, we return False.

Python solution:

1
2
3
4
5
6
7
8
9
class Solution:
    def checkString(self, s: str) -> bool:
        last_a = s.rfind('a')
        first_b = s.find('b')

        if last_a < first_b or first_b == -1 or last_a == -1:
            return True
        else:
            return False

In this code, s.rfind('a') gives us the index of the last occurrence of ‘a’, and s.find('b') gives us the index of the first occurrence of ‘b’. The if condition checks if the last occurrence of ‘a’ is before the first occurrence of ‘b’. If there are no ‘a’s or ‘b’s in the string, s.rfind('a') or s.find('b') will return -1, which means every ‘a’ is before every ‘b’.