Skip to content

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

Description

Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.

 

Example 1:

Input: s = "aaabbb"
Output: true
Explanation:
The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.
Hence, every 'a' appears before every 'b' and we return true.

Example 2:

Input: s = "abab"
Output: false
Explanation:
There is an 'a' at index 2 and a 'b' at index 1.
Hence, not every 'a' appears before every 'b' and we return false.

Example 3:

Input: s = "bbb"
Output: true
Explanation:
There are no 'a's, hence, every 'a' appears before every 'b' and we return true.

 

Constraints:

  • 1 <= s.length <= 100
  • s[i] is either 'a' or 'b'.

Solutions

Solution 1: Brain Teaser

According to the problem statement, the string \(s\) consists only of characters a and b.

To ensure that all as appear before all bs, the condition that must be met is that b should not appear before a. In other words, the substring "ba" should not be present in the string \(s\).

The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(1)\).

1
2
3
class Solution:
    def checkString(self, s: str) -> bool:
        return "ba" not in s
1
2
3
4
5
class Solution {
    public boolean checkString(String s) {
        return !s.contains("ba");
    }
}
1
2
3
4
5
6
class Solution {
public:
    bool checkString(string s) {
        return !s.contains("ba");
    }
};
1
2
3
func checkString(s string) bool {
    return !strings.Contains(s, "ba")
}
1
2
3
function checkString(s: string): boolean {
    return !s.includes('ba');
}
1
2
3
4
5
impl Solution {
    pub fn check_string(s: String) -> bool {
        !s.contains("ba")
    }
}

Comments