Skip to content

Instantly share code, notes, and snippets.

@bchetty
Created May 23, 2013 22:22
Show Gist options
  • Save bchetty/5639936 to your computer and use it in GitHub Desktop.
Save bchetty/5639936 to your computer and use it in GitHub Desktop.
T9Spelling - GCJ 2010 (Africa)
import java.util.*;
import java.io.*;
public class T9Spelling {
public String translate(String phrase) {
HashMap<String, String> alphaMap = getKeypadDictionary();
StringBuilder sbTranslatedMessage = new StringBuilder();
for(int i=0;i<phrase.length();i++) {
if(i != 0) {
String str1 = alphaMap.get("" + phrase.charAt(i-1));
String str2 = alphaMap.get("" + phrase.charAt(i));
sbTranslatedMessage.append((str1.charAt(0) == str2.charAt(0)) ? " " + alphaMap.get("" + phrase.charAt(i)) :
alphaMap.get("" + phrase.charAt(i)));
} else {
sbTranslatedMessage.append(alphaMap.get("" + phrase.charAt(i)));
}
}
return sbTranslatedMessage.toString();
}
private HashMap<String, String> getKeypadDictionary() {
HashMap<String, String> alphaMap = new HashMap<String, String>();
alphaMap.put(" ", "0");
alphaMap.put("a", "2");
alphaMap.put("b", "22");
alphaMap.put("c", "222");
alphaMap.put("d", "3");
alphaMap.put("e", "33");
alphaMap.put("f", "333");
alphaMap.put("g", "4");
alphaMap.put("h", "44");
alphaMap.put("i", "444");
alphaMap.put("j", "5");
alphaMap.put("k", "55");
alphaMap.put("l", "555");
alphaMap.put("m", "6");
alphaMap.put("n", "66");
alphaMap.put("o", "666");
alphaMap.put("p", "7");
alphaMap.put("q", "77");
alphaMap.put("r", "777");
alphaMap.put("s", "7777");
alphaMap.put("t", "8");
alphaMap.put("u", "88");
alphaMap.put("v", "888");
alphaMap.put("w", "9");
alphaMap.put("x", "99");
alphaMap.put("y", "999");
alphaMap.put("z", "9999");
return alphaMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment