forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAlphabetical.java
More file actions
32 lines (30 loc) · 1.13 KB
/
Alphabetical.java
File metadata and controls
32 lines (30 loc) · 1.13 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
package com.thealgorithms.strings;
/**
* Utility class for checking if a string's characters are in alphabetical order.
* <p>
* Alphabetical order is a system whereby character strings are placed in order
* based on the position of the characters in the conventional ordering of an
* alphabet.
* <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 alphabetical order.
* Non-letter characters will cause the check to fail.
*
* @param s the input string
* @return {@code true} if all characters are in alphabetical order (case-insensitive), otherwise {@code false}
*/
public static boolean isAlphabetical(String s) {
s = s.toLowerCase();
for (int i = 0; i < s.length() - 1; ++i) {
if (!Character.isLetter(s.charAt(i)) || s.charAt(i) > s.charAt(i + 1)) {
return false;
}
}
return !s.isEmpty() && Character.isLetter(s.charAt(s.length() - 1));
}
}