Skip to content

Commit 1ea9f49

Browse files
Enhance Alphabetical.isAlphabetical with null and empty string check
1 parent 3eb521b commit 1ea9f49

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/main/java/com/thealgorithms/strings/Alphabetical.java

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,17 @@ private Alphabetical() {
2121
* @return {@code true} if all characters are in alphabetical order (case-insensitive), otherwise {@code false}
2222
*/
2323
public static boolean isAlphabetical(String s) {
24+
if (s == null || s.isEmpty()) {
25+
return false;
26+
}
2427
s = s.toLowerCase();
25-
for (int i = 0; i < s.length() - 1; ++i) {
26-
if (!Character.isLetter(s.charAt(i)) || s.charAt(i) > s.charAt(i + 1)) {
28+
for (int i = 0; i < s.length() - 1; i++) {
29+
char current = s.charAt(i);
30+
char next = s.charAt(i + 1);
31+
if (!Character.isLetter(current) || current > next) {
2732
return false;
2833
}
2934
}
30-
return !s.isEmpty() && Character.isLetter(s.charAt(s.length() - 1));
35+
return Character.isLetter(s.charAt(s.length() - 1));
3136
}
3237
}

0 commit comments

Comments
 (0)