-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathAlphabetical.java
More file actions
58 lines (50 loc) · 1.75 KB
/
Alphabetical.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
package com.thealgorithms.strings;
import java.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>
*/
public final class Alphabetical {
private Alphabetical() {
}
/**
* 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}
*/
public static boolean isAlphabetical(String s) {
if (s == null || s.isBlank()) {
return false;
}
String normalized = s.toLowerCase(Locale.ROOT);
if (!Character.isLetter(normalized.charAt(0))) {
return false;
}
for (int i = 1; i < normalized.length(); i++) {
char prev = normalized.charAt(i - 1);
char curr = normalized.charAt(i);
if (!Character.isLetter(curr) || prev > curr) {
return false;
}
}
return true;
}
}