Leetcode 2124. Check if All A’s Appears Before All B’s
s consisting only of the characters ‘a’ and ‘b’, check if all the ‘a’ characters appear before all the ‘b’ characters in the string.Example:
Input: "aaabbb"
Output: true
Input: "abab"
Output: false
s?true and false?Assuming:
s will only contain ‘a’ and ‘b’.We need to iterate through the string and check if at any position a character ‘b’ is followed by a character ‘a’. This would mean that ‘a’ does not appear before all ‘b’s, and we should return false in that case.
seenB to false.seenB to true.seenB is true, return false immediately.true.class Solution {
public:
bool checkString(string s) {
bool seenB = false;
for (char c : s) {
if (c == 'b') {
seenB = true;
} else if (c == 'a') {
if (seenB) {
return false;
}
}
}
return true;
}
};
This solution is efficient since it only requires a single pass through the input string, ensuring optimal performance.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?