Skip to content

Instantly share code, notes, and snippets.

@Samee24
Last active August 29, 2015 14:26
Show Gist options
  • Save Samee24/8cc19ca309ab2aa258a2 to your computer and use it in GitHub Desktop.
Save Samee24/8cc19ca309ab2aa258a2 to your computer and use it in GitHub Desktop.
public static boolean isInOrder(String input, String ordering) {
class PairChar {
int first = Integer.MAX_VALUE;
int last = -1;
}
char[] orderArr = ordering.toCharArray();
char[] inputArr = input.toCharArray();
HashMap<Character, PairChar> map = new HashMap<>();
for (int i = 0; i < inputArr.length; i++) {
PairChar pair = map.get(inputArr[i]);
if (pair == null) {
pair = new PairChar();
pair.first = i;
pair.last = i;
map.put(inputArr[i], pair);
} else {
pair.last = i;
map.put(inputArr[i], pair);
}
}
PairChar prevPair = new PairChar();
PairChar currentPair;
for (char ordrChr : orderArr) {
if (map.get(ordrChr)== null) {
return false; //case when input has NO elements of order string
}
currentPair= map.get(ordrChr);
if (prevPair.last > currentPair.first) {
return false;
} else {
prevPair = currentPair;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment