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.
This program checks whether every 'a' in the given string `s`, which consists only of characters 'a' and 'b', appears before every 'b'. The goal is to ensure that there is no occurrence of 'b' followed by 'a' in the string. The code iterates through the string to verify this condition, returning `true` if the condition holds and `false` otherwise.
The solution begins by calculating the size of the string `s` using `s.size()`. Then, it uses a loop to traverse the string from the first character to the second-to-last character (indices 0 to \(n-2\)). Within the loop, the program checks for any occurrence of the character 'b' (ASCII value 98) at index `i` followed immediately by a character other than 'b' at index `i+1`. This condition ensures that if a 'b' is encountered, no subsequent 'a' can follow. If such a case is found, the program immediately returns `false`, as the string violates the rule that all 'a's must appear before all 'b's. If the loop completes without finding this issue, the program returns `true`, indicating the string meets the condition.
For example, consider the input `s = "aaabbb"`. The loop will iterate through the string, comparing adjacent characters. Since no 'b' is followed by an 'a', the function returns `true`. In the case of `s = "abab"`, the loop detects that the 'b' at index 1 is followed by an 'a' at index 2, violating the condition, so it returns `false`. For `s = "bbb"`, there are no 'a's in the string, so the function returns `true`, as the condition is trivially satisfied.
This approach efficiently verifies the condition with a time complexity of \(O(n)\), where \(n\) is the length of the string, as it processes the string in a single pass. The space complexity is \(O(1)\) because it does not use any additional data structures. This solution works well for strings of any length and handles edge cases such as strings with no 'a's, no 'b's, or a single character. It ensures correctness by relying solely on logical checks without unnecessary operations.
CODE:
0 Comments