Created
February 25, 2021 13:50
-
-
Save sgabber/87f0949b2af15845768a746720be574b to your computer and use it in GitHub Desktop.
Converts phone digits to string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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