-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathDetectCapital.java
More file actions
36 lines (27 loc) · 819 Bytes
/
DetectCapital.java
File metadata and controls
36 lines (27 loc) · 819 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Source: https://leetcode.com/problems/detect-capital/
Time: O(n), where n is the length of the given String(word)
Space: O(n), we need a char array(ch) of size equal to the length of the given String(word) to access each character
*/
class Solution {
public boolean detectCapitalUse(String word) {
int len = word.length();
char[] ch = word.toCharArray();
boolean isFirstLastCharCapital = isLetterCapital(ch[0]) && isLetterCapital(ch[len - 1]);
for(int i = 1; i < len; ++i) {
if(isFirstLastCharCapital) {
if(!isLetterCapital(ch[i])) {
return false;
}
} else {
if(isLetterCapital(ch[i])) {
return false;
}
}
}
return true;
}
private boolean isLetterCapital(char ch) {
return ch >= 'A' && ch <= 'Z';
}
}