标签:telephone possible letters number public
Total Accepted: 39162 Total Submissions: 151116My Submissions
Question Solution
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
分析:我们使用栈依次存储电话号码,对每一个号码有多种选择,当选择完全,该号码才被弹出,因此针对号码,我们设计了class tuple, 该类中含有当前选项cur和,选项集合size构成。
public class Solution {
List<String> x=new ArrayList<String>();
String[] disp=new String[9];
public void OutResult(Stack stack, int l, String dstr){
Stack<tuple> ss = new Stack<tuple>();
String str="";
int m=l;
while(!stack.isEmpty())
{
tuple z=(tuple)stack.peek();
m--;
str=String.valueOf(disp[dstr.charAt(m)-‘1‘].charAt(z.cur))+str;
ss.push(z);
stack.pop();
}
while(!ss.isEmpty())
{
tuple z=(tuple)ss.peek();
stack.push(z);
ss.pop();
}
x.add(str);
}
public List<String> letterCombinations(String digits) {
x=new ArrayList<String>();
//下面是号码表,即号码对应的字符信息
disp[0]="";
disp[1]="abc";
disp[2]="def";
disp[3]="ghi";
disp[4]="jkl";
disp[5]="mno";
disp[6]="pqrs";
disp[7]="tuv";
disp[8]="wxyz";
if(digits.length()==0)
return x;
else
{
int l=digits.length();
int i=1;
Stack<tuple> stack = new Stack<tuple>();
char c=digits.charAt(i-1);
int ll=disp[c-‘1‘].length();
tuple y=new tuple(ll);
stack.push(y);
while(!stack.isEmpty()){
if(i<l)
{
i++;
y=new tuple(disp[digits.charAt(i-1)-‘1‘].length());
stack.push(y);
}
else
{
OutResult(stack,l,digits);
tuple z=(tuple)stack.peek();
while(z.cur+1==z.size&&i>1)
{
i--;
stack.pop();
z=(tuple)stack.peek();
}
if(z.cur+1==z.size&&i==1)
break;
else
{
stack.pop();
z.cur++;
stack.push(z);
}
}
}
return x;
}
}
}
class tuple{
public int cur;
public int size;
tuple(int s){
cur=0;
size=s;
}
}
Leetcode#17Letter Combinations of a Phone Number
标签:telephone possible letters number public
原文地址:http://7061299.blog.51cto.com/7051299/1652478