手机键盘每个数字对应的字符如下:
0 ---> "0";
1 ---> "1";
2 --- > "ABC2";
3 ---> "DEF3";
4 ---> "GHI4";
5 ---> "JKL5";
6 ---> "MNO6";
7 ---> "PQRS7";
8 ---> "TUV8";
9 ---> "WXYZ9";
* ---> 空格;
# ---> 断开;
比如,输入为
222 ---> C,
222222 ---> B
22233 ---> CE
222#33 ---> CE
222*33 ---> C E
2#3*4*4 ---> AD G G
问题:
现在给你一串字符输入,把它转化成为短消息内容。
分析:
其实,这个问题只需要对三种情况进行处理:当字符为 #, 当字符为 * 或者前后字符不一样的时候。只是处理的时候,需要小心,要注意一些特殊情况,比如特殊字符在前面:###33,最后一个是特殊字符:3*** 等。
public class TouchPad {
public static final String[] keypad = {"0", "1", "ABC2", "DEF3", "GHI4", "JKL5", "MNO6", "PQRS7", "TUV8", "WXYZ9"};
public static void main(String[] args) {
System.out.println(process("****##1233456789*******"));
}
public static String process(String in) {
if (in == null || in.length() == 0) return in;
char prev = ' ';
int count = -1;
String result = "";
for (int i = 0; i < in.length(); i++) {
char current = in.charAt(i);
if (current == prev) {
count++;
} else {
result += getResult(prev, count);
if (current >= '0' && current <= '9') {
prev = current;
count = 0;
} else {
prev = ' ';
count = -1;
if (current == '*') {
result += " ";
}
}
}
}
result += getResult(prev, count);
return result;
}
public static String getResult(char prev, int count) {
if (prev == ' ') return "";
String sequences = keypad[prev - '0'];
count %= sequences.length();
char ch = sequences.charAt(count);
return ch + "";
}
}