refactor: refactor Alphabetical and AlphabeticalTest (#6355)

This commit is contained in:
Oleksandr Klymenko
2025-07-10 18:52:38 +03:00
committed by GitHub
parent 22cba2c84f
commit f3252793e1
2 changed files with 19 additions and 38 deletions

View File

@@ -1,36 +1,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. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order
* alphabet.
* <p>
* Reference: <a href="https://en.wikipedia.org/wiki/Alphabetical_order">Wikipedia: Alphabetical Order</a>
*/
final class Alphabetical {
public final class Alphabetical {
private Alphabetical() {
}
public static void main(String[] args) {
assert !isAlphabetical("123abc");
assert isAlphabetical("aBC");
assert isAlphabetical("abc");
assert !isAlphabetical("xyzabc");
assert isAlphabetical("abcxyz");
}
/**
* Check if a string is alphabetical order or not
* Checks whether the characters in the given string are in alphabetical order.
* Non-letter characters will cause the check to fail.
*
* @param s a string
* @return {@code true} if given string is alphabetical order, otherwise
* {@code false}
* @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))) {
if (!Character.isLetter(s.charAt(i)) || s.charAt(i) > s.charAt(i + 1)) {
return false;
}
}
return true;
return !s.isEmpty() && Character.isLetter(s.charAt(s.length() - 1));
}
}