520. Detect Capital
Explanation
To solve this problem, we need to check if the usage of capitals in the given word is right according to the defined rules. We can achieve this by checking the following conditions:
- If all letters are capitals.
- If all letters are lowercase.
- If only the first letter is capital.
We can iterate through the characters of the word and count the number of uppercase characters and the position of the first uppercase character. Based on these counts, we can determine if the capital usage is right.
- Time complexity: O(n) where n is the length of the input word.
- Space complexity: O(1)
class Solution {
public boolean detectCapitalUse(String word) {
int n = word.length();
int upperCount = 0;
int firstUpperIndex = -1;
for (int i = 0; i < n; i++) {
char ch = word.charAt(i);
if (Character.isUpperCase(ch)) {
upperCount++;
if (i == 0) {
firstUpperIndex = 0;
}
}
}
if (upperCount == n || upperCount == 0 || (upperCount == 1 && firstUpperIndex == 0)) {
return true;
}
return false;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.