-
Notifications
You must be signed in to change notification settings - Fork 17
/
CheckCapitalUsage.java
54 lines (47 loc) · 1.63 KB
/
CheckCapitalUsage.java
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package by.andd3dfx.string;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
/**
* <pre>
* <a href="https://leetcode.com/problems/detect-capital/description/">Task description</a>
*
* We define the usage of capitals in a word to be right when one of the following cases holds:
*
* All letters in this word are capitals, like "USA".
* All letters in this word are not capitals, like "leetcode".
* Only the first letter in this word is capital, like "Google".
*
* Given a string word, return true if the usage of capitals in it is right.
*
* Example 1:
*
* Input: word = "USA"
* Output: true
*
* Example 2:
*
* Input: word = "FlaG"
* Output: false
* </pre>
*
* @see <a href="https://youtu.be/v0EkBQbFQpk">Video solution</a>
*/
public class CheckCapitalUsage {
public boolean isCapitalUsedProperly(String word) {
var uppercase = word.toUpperCase();
var lowercase = word.toLowerCase();
var onlyFirstLetterCapitalized = buildWordWithFirstLetterCapitalized(word);
return new HashSet<>(List.of(uppercase, lowercase, onlyFirstLetterCapitalized))
.contains(word);
}
private String buildWordWithFirstLetterCapitalized(String word) {
var chars = word.toLowerCase().toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
private final static Pattern PATTERN = Pattern.compile("^([A-Z]*|[A-Z]?[a-z]*)$");
public boolean isCapitalUsedProperly_withRegex(String word) {
return PATTERN.matcher(word).find();
}
}