Purpose
This problem comes from this question on the dailyprogrammer subreddit.
Basically, the task is to write an implementation that identifies if the characters in a String
are in
- Alphabetical order (A to Z)
- Reverse Alphabetical order (Z to A)
- Neither Alphabetical nor Reverse Alphabetical order (
"abba"
) - Both Alphabetical and Reverse Alphabetical order (only one distinct character in
String
)
Implementation
public class StringCharactersInAlphabeticalOrderEvaluatorImpl implements StringCharactersInAlphabeticalOrderEvaluator {
private final List<Character> charactersFromAtoZ;
public StringCharactersInAlphabeticalOrderEvaluatorImpl(final List<Character> charactersFromAtoZ) {
this.charactersFromAtoZ = charactersFromAtoZ;
}
@Override public AlphabeticalOrderState evaluateAlphabeticalOrderOfCharacters(final String candidate) {
final char[] stringChars = candidate.toUpperCase().toCharArray();
int index = 0;
boolean fromAtoZ = true;
boolean fromZtoA = true;
while (index < stringChars.length - 1) {
if (charactersFromAtoZ.indexOf(stringChars[index]) > charactersFromAtoZ.indexOf(stringChars[index + 1])) {
fromAtoZ = false;
}
if (charactersFromAtoZ.indexOf(stringChars[index]) < charactersFromAtoZ.indexOf(stringChars[index + 1])) {
fromZtoA = false;
}
index++;
}
if (!fromAtoZ && !fromZtoA) {
return AlphabeticalOrderState.IN_NEITHER_ALPHABETICAL_NOR_REVERSE_ALPHABETICAL_ORDER;
}
if (fromAtoZ && fromZtoA) {
return AlphabeticalOrderState.IN_BOTH_ALPHABETICAL_AND_REVERSE_ALPHABETICAL_ORDER;
}
if (fromAtoZ) {
return AlphabeticalOrderState.IN_ALPHABETICAL_ORDER;
}
if (fromZtoA) {
return AlphabeticalOrderState.IN_REVERSE_ALPHABETICAL_ORDER;
}
throw new RuntimeException("unexpected character string");
}
}
Feedback
I'd like feedback on my implementation, specifically
- Am I missing any corner cases? Am I over-specifying my cases (for example, the
BothAlphabeticalAndReverseAlphabetical
case)? - Is this the most efficient way of implementing a solution? Is there a better implementation technique (particularly when it comes to my
if
statements, which I'm not in love with).