Leetcode 2124: Check if All A's Appears Before All B's
You are given a string consisting of only the characters ‘a’ and ‘b’. Your task is to determine if all occurrences of ‘a’ appear before all occurrences of ‘b’ in the string. If that is the case, return true; otherwise, return false.
Problem
Approach
Steps
Complexity
Input: You are given a string s consisting of only the characters 'a' and 'b'.
Example: s = 'aaaabbb'
Constraints:
• 1 <= s.length <= 100
• s[i] is either 'a' or 'b'.
Output: Return true if every 'a' appears before every 'b' in the string. Otherwise, return false.
Example: Input: 'aaabbb' -> Output: true
Constraints:
• The input string will contain only 'a' and 'b'.
Goal: Determine if all 'a' characters in the string appear before all 'b' characters.
Steps:
• Check if the substring 'ba' exists in the string.
• If 'ba' is found, return false. Otherwise, return true.
Goal: The string will have a length between 1 and 100, and each character will be either 'a' or 'b'.
Steps:
• The string length is between 1 and 100.
• The string contains only the characters 'a' and 'b'.
Assumptions:
• The string contains only 'a' and 'b'.
• There will be at least one character in the string.
• Input: Input: 'aaaabbb'
• Explanation: In this case, all the 'a's appear before the 'b's, so we return true.
• Input: Input: 'abab'
• Explanation: Here, an 'a' appears after a 'b', so we return false.
Approach: To solve this problem, check if the substring 'ba' exists in the input string. If it does, it means there is a 'b' before an 'a', which violates the condition.
Observations:
• We only need to check if the substring 'ba' is present in the string.
• If 'ba' is found in the string, return false. Otherwise, return true.
Steps:
• Search for the substring 'ba' in the string.
• If 'ba' is found, return false.
• If 'ba' is not found, return true.
Empty Inputs:
• An empty string is not a valid input according to the problem constraints.
Large Inputs:
• Ensure that the solution works for strings with up to 100 characters.
Special Values:
• Strings that consist only of 'a's or 'b's will automatically return true.
Constraints:
• The solution should handle the maximum string length efficiently.
bool checkString(string s) {
return s.find("ba")==string::npos;
}
1 : Function Definition
bool checkString(string s) {
This line defines a function named checkString, which takes a string 's' as input and returns a boolean value.
2 : String Search
return s.find("ba")==string::npos;
This line searches for the substring 'ba' in the input string 's'. If 'ba' is not found, the function returns true; otherwise, it returns false.
Best Case: O(n)
Average Case: O(n)
Worst Case: O(n)
Description: We check if 'ba' exists in the string, which takes O(n) time, where n is the length of the string.
Best Case: O(1)
Worst Case: O(1)
Description: The solution uses a constant amount of extra space.
LeetCode Solutions Library / DSA Sheets / Course Catalog |
---|
comments powered by Disqus