The problem “520. Detect Capital” from LeetCode is defined as follows:
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
Otherwise, we define that this word doesn’t use capitals in a right way.
Example 1:
Input: "USA"
Output: True
Example 2:
Input: "FlaG"
Output: False
Q: Can the input string be empty? A: No, the input string will contain at least one letter.
Q: Will the input string contain non-alphabetic characters? A: No, the input string will only contain alphabetic characters.
Q: Is the input string limited to a specific length? A: The problem constraints do not specify a maximum length, but typical constraints apply (< 1000 characters).
To solve this problem, we need to check the given string against the specified capitalization conditions:
We can implement a function that checks these conditions in sequence.
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool detectCapitalUse(string word) {
// Check if all characters are uppercase
if (all_of(word.begin(), word.end(), ::isupper)) {
return true;
}
// Check if all characters are lowercase
if (all_of(word.begin(), word.end(), ::islower)) {
return true;
}
// Check if only the first character is uppercase and the rest are lowercase
if (isupper(word[0]) && all_of(word.begin() + 1, word.end(), ::islower)) {
return true;
}
// If none of the conditions are met, return false
return false;
}
};
int main() {
Solution sol;
// Test cases
cout << boolalpha; // Print boolean values as true/false instead of 1/0
cout << sol.detectCapitalUse("USA") << endl; // true
cout << sol.detectCapitalUse("leetcode") << endl; // true
cout << sol.detectCapitalUse("Google") << endl; // true
cout << sol.detectCapitalUse("FlaG") << endl; // false
cout << sol.detectCapitalUse("g") << endl; // true
cout << sol.detectCapitalUse("A") << endl; // true
cout << sol.detectCapitalUse("uSa") << endl; // false
return 0;
}
all_of
algorithm to determine if all characters in the string are uppercase.all_of
algorithm to check if all characters are lowercase.all_of
.If any of these conditions are true, the function returns true
, otherwise false
.
The time complexity of this solution is ( O(n) ) where ( n ) is the length of the input string. This is because each all_of
call runs in linear time relative to the number of characters in the string. There are at most three sequential calls, making the overall complexity linear.
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?