[사진 출처: http://tctechcrunch2011.files.wordpress.com/2009/01/microsoft.jpg]
Microsoft 에서 준다는 인터뷰 문제를 풀어 봤어요. 전화번호를 어떤 식으로 저장 시킬지 결정하는게 제일 고민했던 부분이였던것 같습니다. 처음에는 숫자를 키로 하고 알파벳을 값으로 해서 맵핑을 해봤는데 아무래도 그럴려면 효율적이지 몰라도 간단한 문제를 너무 복잡하게 만드는것 같았어요. 그래서 그냥 HashMap 쓰고 알파벳을 키로 하고 숫자를 값으로 하고 푸는 방식으로 했어요. 역시 Data Structure 가 중요한듯.
문제
Print the actual phone number when given an alphanumeric phone number. For e.g. an input of 1-800-COM-CAST should give output as 18002662678. (note output does not contain any special characters like "-")
해석: 전화번호가 입력 가격으로 주어지는데 dash (-) 같은 여러가지 숫자가 아닌 심벌들이 섞여 있을수 있어요. 그리고 1-800-COM-CAST 처럼 숫자된지 알파벳이 들어간 전화번호는 해당되는 숫자에 바꾸어서 출력해야 됩니다.
새가지 함수를 만들었습니다. initPhoneMapping(), removeSpecialChars(), 그리고 getFormattedPhoneNumber() 와 같아요. initPhoneMapping() 은 처음에 클래스가 initialize 될때 알파벳을 전화번호에 해당되는 숫자에 멥핑하는 역활을 합니다. 그리고 removeSpecialChars() 는 dash 같은 필요없는 심벌들을 없애버린 String 오브젝트를 리턴해요. 마지막으로 getFormattedPhoneNumber() 함수는 initPhoneMapping() 과 removeSpecialChars() 를 불러내고 알파벳을 전화번호로 바꾼 String 오브젝트 가격을 caller 에게 리턴하는 걸로 끝이에요.
솔류션은 자바로 되어 있습니다.
package com.practice; import java.util.HashMap; public class FormatedPhoneNumberTest { private static HashMap mapAlphaPhone = initPhoneMapping(); public static void main(String[] args) { FormatedPhoneNumberTest fpnt = new FormatedPhoneNumberTest(); String phoneNumber = "1-800-COM-CAST"; System.out.println("Before: " + phoneNumber); System.out.println("After: " + fpnt.getFormattedPhoneNumber(phoneNumber)); } public String getFormattedPhoneNumber(String phoneNumber) { phoneNumber = removeSpecialChars(phoneNumber); StringBuffer sf = new StringBuffer(); for(int i=0; i < phoneNumber.length(); ++ i) { String iString = phoneNumber.substring(i, i + 1); if(mapAlphaPhone.containsKey(iString)) { sf.append(mapAlphaPhone.get(iString)); } else { sf.append(iString); } } return sf.toString(); } public String removeSpecialChars(String str) { str = str.replace("-", ""); str = str.replace(".", ""); str = str.replace("(", ""); str = str.replace(")", ""); return str; } public static HashMap initPhoneMapping() { HashMap hashMap = new HashMap(); hashMap.put("A",2); hashMap.put("B",2); hashMap.put("C",2); hashMap.put("D",3); hashMap.put("E",3); hashMap.put("F",3); hashMap.put("G",4); hashMap.put("H",4); hashMap.put("I",4); hashMap.put("J",5); hashMap.put("K",5); hashMap.put("L",5); hashMap.put("M",6); hashMap.put("N",6); hashMap.put("O",6); hashMap.put("P",7); hashMap.put("Q",7); hashMap.put("R",7); hashMap.put("S",7); hashMap.put("T",8); hashMap.put("U",8); hashMap.put("V",8); hashMap.put("W",9); hashMap.put("X",9); hashMap.put("Y",9); hashMap.put("Z",9); return hashMap; } }
'프로그래밍 > 코딩 연습 ' 카테고리의 다른 글
[구글 코딩 잼] Magic Trick - Qualification Round Problem 1 (0) | 2014.05.03 |
---|---|
아마존 닷컴 (Amazon.com) 코딩 연습 문제 - Non Repeating Character (0) | 2014.01.26 |
구글 코딩 잼 연습 - Store Credit 솔류션 (0) | 2014.01.23 |
구글 코딩 잼 연습 - Reverse Words 솔류션 (0) | 2014.01.22 |