Skip to content

Instantly share code, notes, and snippets.

@kylelong
Created March 3, 2019 03:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylelong/31bb7b4e04aeaa4fa9e0200e49efaab3 to your computer and use it in GitHub Desktop.
Save kylelong/31bb7b4e04aeaa4fa9e0200e49efaab3 to your computer and use it in GitHub Desktop.
Cassido's weekly newsletter interview question of the week 2/24/19
import java.util.*;
/**
* Created by kylel95 on 3/1/19.
*/
public class phonePad {
public static void main(String [] args){
String s = "123456";
perm1(makeString(s));
}
/**
* @param s Phone number to permute
* @return Permuted string based on number to letters mapping on a phone pad
*/
public static String makeString(String s){
HashMap<Character, String> phone = new HashMap<>();
StringBuilder sb = new StringBuilder();
phone.put('0', "");
phone.put('1', "");
phone.put('2', "ABC");
phone.put('3', "DEF");
phone.put('4', "GHI");
phone.put('5', "JKL");
phone.put('6', "MNO");
phone.put('7', "PQRS");
phone.put('8', "TUV");
phone.put('9', "WXYZ");
for(int i = 0; i < s.length(); i++){
sb.append(phone.get(s.charAt(i)));
}
return sb.toString();
}
/**
* Helper permutation method to calculate permutations of a string
* //https://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html
// print n! permutation of the characters of the string s (in order)
* @param s String to permute
*/
public static void perm1(String s) { perm1("", s); }
/**
* Calculates all s.length! permutation of a string
* @param prefix prefix being appended to from the permuted string s
* @param s String to be permuted
*/
private static void perm1(String prefix, String s) {
int n = s.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, n));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment