Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathAlphabetical.java
More file actions
Latest commit
58 lines (50 loc) · 1.75 KB
/
Copy pathAlphabetical.java
File metadata and controls
58 lines (50 loc) · 1.75 KB
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
55
56
57
58
packagecom.thealgorithms.strings;
importjava.util.Locale;
/**
* Utility class for checking whether a string's characters are in non-decreasing
* lexicographical order based on Unicode code points (case-insensitive).
* <p>
* This does NOT implement language-aware alphabetical ordering (collation rules).
* It simply compares lowercase Unicode character values.
* <p>
* Non-letter characters are not allowed and will cause the check to fail.
* <p>
* Reference:
* <a href="https://en.wikipedia.org/wiki/Alphabetical_order">Wikipedia: Alphabetical order</a>
*/
publicfinalclassAlphabetical {
privateAlphabetical() {
}
/**
* Checks whether the characters in the given string are in non-decreasing
* lexicographical order (case-insensitive).
* <p>
* Rules:
* <ul>
* <li>String must not be null or blank</li>
* <li>All characters must be letters</li>
* <li>Comparison is based on lowercase Unicode values</li>
* <li>Order must be non-decreasing (equal or increasing allowed)</li>
* </ul>
*
* @param s input string
* @return {@code true} if characters are in non-decreasing order, otherwise {@code false}
*/
publicstaticbooleanisAlphabetical(Strings) {
if (s == null || s.isBlank()) {
returnfalse;
}
Stringnormalized = s.toLowerCase(Locale.ROOT);
if (!Character.isLetter(normalized.charAt(0))) {
returnfalse;
}
for (inti = 1; i < normalized.length(); i++) {
charprev = normalized.charAt(i - 1);
charcurr = normalized.charAt(i);
if (!Character.isLetter(curr) || prev > curr) {
returnfalse;
}
}
returntrue;
}
}