电话号码的字母组合-lintcode

来源:互联网 发布:c语言快速排序算法代码 编辑:程序博客网 时间:2024/04/30 15:39

Given a digit string excluded 01, 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.

Cellphone

 注意事项

以上的答案是按照词典编撰顺序进行输出的,不过,在做本题时,你也可以任意选择你喜欢的输出顺序。

样例

给定 "23"

返回 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

该题首先是要创建一个数字所对应的字典,根据字典中的字母来组合成不同的字符串。


 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution
{
public:
    
/**
     * @param digits A digital string
     * @return all posible letter combinations
     */

    vector<string> letterCombinations(string &digits)
    {
        
// Write your code here
        vector<string> res;
        
if (digits.size() == NULL || digits == "01" || digits == "10"return res;
        string s[] = { 
"""""abc""def""ghi""jkl""mno""pqrs""tuv""wxyz" };
        res.push_back(
"");
        
for (int i = 0; i < digits.size(); i++)
        {
            
int n = res.size();
            string s0 = s[digits[i] - 
'0'];
            
for (int j = 0; j < n; j++)
            {
                string temp = res.front();
                res.erase(res.begin());//依次取出res中的每一个字符,然后与s0中的字符组合
                
for (int k = 0; k < s0.size(); k++)
                {
                    res.push_back(temp + s0[k]);
                }
            }
        }
        
return res;
    }
};
原创粉丝点击