Skip to content

Instantly share code, notes, and snippets.

@aravindc26
Created August 31, 2012 10:13
Show Gist options
  • Save aravindc26/3551122 to your computer and use it in GitHub Desktop.
Save aravindc26/3551122 to your computer and use it in GitHub Desktop.
mobile keypad
package test.decodethecode;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class DecodeTheCode {
HashMap<String, String> encodings = new HashMap<String, String>();
public void hashInit() {
//create hash table
encodings.put("2", "a");encodings.put("22", "b");encodings.put("222", "c");
encodings.put("3", "d");encodings.put("33", "e");encodings.put("333", "f");
encodings.put("4", "g");encodings.put("44", "h");encodings.put("444", "i");
encodings.put("5", "j");encodings.put("55", "k");encodings.put("555", "l");
encodings.put("6", "m");encodings.put("66", "n");encodings.put("666", "o");
encodings.put("7", "p");encodings.put("77", "q");encodings.put("777", "r");
encodings.put("7777", "s");encodings.put("8", "t");encodings.put("88", "u");
encodings.put("888", "v");encodings.put("8888", "8");encodings.put("9", "w");
encodings.put("99", "x");encodings.put("999", "y");encodings.put("9999", "z");
encodings.put("0", " ");
}
public String decodeCode(String encodedString) {
StringBuilder resultInEachStep = new StringBuilder();
hashInit();
//pattern checking for a valid input
boolean flag = Pattern.matches("(((\\d)\\3*)(#\\3)?)+", encodedString);
if(!flag)
return null; //string invalid
Pattern p = Pattern.compile("(\\d)\\1*");
Matcher m = p.matcher(encodedString);
while(m.find()){
resultInEachStep.append(encodings.get(m.group(0)));
}
return resultInEachStep.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment