码迷,mamicode.com
首页 > 其他好文 > 详细

Letter Combinations of a Phone Number -- leetcode

时间:2014-12-23 19:40:19      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:leetcode   面试   数字组合   电话号码   phone   

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"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.


算法一: 用数制进位的思维做组合。

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        const char *map[] = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        int idx[sizeof(map)/sizeof(map[0])] = {0};
        vector<string> result;
        string item;
        bool carry = false;
        while (!carry) {
                item.clear();
                carry = true;
                for (int i=0; i<digits.size(); ++i) {
                        const char * p = &map[digits[i]-'0'][idx[i]];
                        if (*p)
                                item.append(1, *p);

                        if (carry && *p) {
                                ++idx[i];
                                ++p;
                                if (!*p)
                                        idx[i] = 0;
                                else
                                        carry = false;
                        }
                }
                result.push_back(item);
        }

        if (result.empty())
                result.push_back(item);

        return result;
    }
};

下面这一句,纯粹是为了满足leetcode的输入为空串("")时的test case:

        if (result.empty())
                result.push_back(item);


看到这算法的执行时间,忍不住做了个截图,留个纪念。

技术分享

算法二,待续


Letter Combinations of a Phone Number -- leetcode

标签:leetcode   面试   数字组合   电话号码   phone   

原文地址:http://blog.csdn.net/elton_xiao/article/details/42105059

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!