Leetcode 2124. Check if All A’s Appears Before All B’s
You are given a string s
consisting of only the characters ‘a’ and ‘b’. You need to determine if every ‘a’ in the string appears before every ‘b’. Return true
if every ‘a’ appears before every ‘b’, otherwise return false
.
The time complexity of this approach is O(n), where n is the length of the string. This is because we only make a single pass through the string.
public class Solution {
public boolean checkString(String s) {
boolean foundB = false;
// Iterate through each character in the string
for (char ch : s.toCharArray()) {
if (ch == 'b') {
foundB = true;
}
// If 'a' is found after 'b', return false
if (foundB && ch == 'a') {
return false;
}
}
// If no 'a' is found after 'b', return true
return true;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Test cases
System.out.println(sol.checkString("aaabbb")); // true
System.out.println(sol.checkString("abab")); // false
System.out.println(sol.checkString("bbb")); // true
System.out.println(sol.checkString("a")); // true
System.out.println(sol.checkString("")); // true (assuming empty is a valid input)
}
}
checkString
method initializes a boolean foundB
to track if a ‘b’ has been encountered.foundB
is set to true.foundB
is true and an ‘a’ is encountered, it returns false immediately.This straightforward approach ensures we efficiently check the condition by a single traversal of the string.
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?