Skip to content

Instantly share code, notes, and snippets.

@sgabber
Created February 25, 2021 13:50
Show Gist options
  • Save sgabber/87f0949b2af15845768a746720be574b to your computer and use it in GitHub Desktop.
Save sgabber/87f0949b2af15845768a746720be574b to your computer and use it in GitHub Desktop.
Converts phone digits to string
import java.util.HashMap;
class Scratch {
public static void main(String[] args) {
String s = "444 2 6 444 66 33 888 444 8 2 22 555 33";
HashMap<String, String> numToLetters = new HashMap<>();
numToLetters.put("2", "abc");
numToLetters.put("3", "def");
numToLetters.put("4", "ghi");
numToLetters.put("5", "jkl");
numToLetters.put("6", "mno");
numToLetters.put("7", "pqrs");
numToLetters.put("8", "tuv");
numToLetters.put("9", "wxyz");
numToLetters.put("0", " ");
String[] split = s.split("");
State st = State.INIT;
String curPress = "";
Integer countPresses = 0;
for (String s1 : split) {
if (st == State.INIT) {
curPress = s1;
countPresses = 1;
st = State.SUBNUMBER;
} else if (curPress.equals(s1)) {
countPresses += 1;
} else if (s1.equals(" ")) {
flush(numToLetters, curPress, countPresses);
curPress = "";
countPresses = 0;
st = State.INIT;
} else {
flush(numToLetters, curPress, countPresses);
curPress = s1;
countPresses = 1;
st = State.SUBNUMBER;
}
}
if (st != State.INIT)
flush(numToLetters, curPress, countPresses);
}
private static void flush(HashMap<String, String> numToLetters, String curPress, Integer countPresses) {
String s2 = numToLetters.get(curPress);
String s3 = s2.split("")[(countPresses - 1) % s2.length()];
System.out.println(s3);
}
enum State {
INIT, SUBNUMBER
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment