Leetcode 520: Detect Capital
Given a word, you need to determine if the usage of capital letters in it is right or not. The usage of capital letters is considered correct in the following cases:
Otherwise, return false.
Example 1:
Example 2:
Note: The input will be a non-empty word consisting of uppercase and lowercase latin letters.
To solve this problem, we need to check the given word against the three valid capital usage patterns mentioned above:
Using Java, this can be achieved by:
Here is the Java code to implement the solution:
class Solution {
public boolean detectCapitalUse(String word) {
// Case 1: All characters are uppercase
if (word.equals(word.toUpperCase())) {
return true;
}
// Case 2: All characters are lowercase
if (word.equals(word.toLowerCase())) {
return true;
}
// Case 3: Only the first character is uppercase and the rest are lowercase
if (Character.isUpperCase(word.charAt(0)) && word.substring(1).equals(word.substring(1).toLowerCase())) {
return true;
}
// If none of the cases match
return false;
}
}
The time complexity of this solution is O(n), where n is the length of the input string. This is due to performing at most three linear scans of the string:
The space complexity is O(1) aside from the input and output, as no additional space proportional to the input size is used other than for auxiliary variables.
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?