import java.util.Arrays;
import java.util.HashMap;
import java.util.TreeSet;
public class T9Input {
public String[] getKeypresses(String[] messages) {
HashMap<String,TreeSet<String>> map = new HashMap<String,TreeSet<String>>();
HashMap dict = new HashMap();
for (int i = 0; i < messages.length; i++) {
String[] sp = messages[i].split(" ");
for (int j = 0; j < sp.length; j++) {
String str = "";
for (int k = 0; k < sp[j].length(); k++) {
int num = 0;
char c = sp[j].charAt(k);
if (c <= 'c') num = 2;
else if (c <= 'f') num = 3;
else if (c <= 'i') num = 4;
else if (c <= 'l') num = 5;
else if (c <= 'o') num = 6;
else if (c <= 's') num = 7;
else if (c <= 'v') num = 8;
else num = 9;
str += num;
}
TreeSet<String> ts = (!map.containsKey(str)) ? new TreeSet<String>() : map.get(str);
ts.add(sp[j]);
map.put(str,ts);
dict.put(sp[j],str);
}
}
String[] res = new String[messages.length];
for (int i = 0; i < messages.length; i++) {
String str = "";
for (int j = 0; j < messages[i].length(); j++) {
if (messages[i].charAt(j) == ' ') {
str += "#";
continue;
}
int j0 = j;
while (j+1 < messages[i].length() && messages[i].charAt(j+1) != ' ') j++;
String word = messages[i].substring(j0,j+1);
str += dict.get(word);
int hash = map.get(dict.get(word)).headSet(word).size();
while (hash-- > 0) str += "0";
}
res[i] = str;
}
return res;
}
}
Explanation
주어진 입력을 가지고 중복 없는 사전을 만들어야 한다.
첫 번째 for문: 맵 구조인 map과 dict를 만들고, map에는 단어를 숫자로 바꾼 것과 변환된 단어가 저장되는 TreeSet을 넣고 dict에는 단어와 숫자를 String 형태로 넣는다.
두 번째 for문: 각 문자를 지정된 문자로 치환한다. 빈칸은 #, 단어는 숫자, 공백은 0으로 표시한다.
최근 덧글