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

LeetCode 力扣

1. Description

Given a string s containing only ‘a’ and ‘b’, determine whether all occurrences of ‘a’ come before all occurrences of ‘b’.
Return true if this ordering holds, and false otherwise. A string containing only one of the two characters satisfies the condition.

2. Example

Example 1

Input: s = “aaabbb”
Output: true
Explanation: Every ‘a’ comes before every ‘b’.

Example 2

Input: s = “abab”
Output: false
Explanation: The ‘a’ at index 2 appears after the ‘b’ at index 1.

Example 3

Input: s = “bbb”
Output: true
Explanation: There are no occurrences of ‘a’, so the ordering condition holds.

3. Constraints

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

4. Solutions

Simulation

n = str.size()
Time complexity: O(n)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    bool checkString(const string &str) {
        bool b_exist = false;
        for (int i = 0, n = str.size(); i < n; ++i) {
            if (str[i] == 'a' && b_exist) {
                return false;
            } else if (str[i] == 'b') {
                b_exist = true;
            }
        }

        return true;
    }
};
comments powered by Disqus