题解——Leetcode 17.Letter Combinations of a Phone Number 难度:Medium

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

C++程序如下:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> res;
        string charmap[10] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        res.push_back("");
        
        if(digits.size() == 0)
            res.clear();
            
        for(int i = 0; i < digits.size(); i++){
            vector<string> tmp;
            string chars = charmap[digits[i]-'0'];
            for(int j = 0; j < chars.size(); j++)
                for(int k = 0; k < res.size(); k++)
                    tmp.push_back(res[k]+chars[j]);
            res = tmp;
        }
        return res;
    }
};

此题题意很好理解,输入为电话号码字符串,输出为电话号码所对应的字母的所有组合可能。

首先,用字符串数组charmap[10]存每个号码对应的字母,由于0和1没有对应的字母,所以对应存空字符串即可。

然后,遍历电话号码字符串,将每个号码对应的所有字母存入字符串chars,接着遍历每个号码对应的可能字母。

最后,考虑边界情况,输入电话号码为空,字母组合也应该为空。为了后面for循环中res.size()大于0,先将空字符串压入res中。所以在判断输入为空后需要res.clear()。


for(int j = 0; j < chars.size(); j++)
for(int k = 0; k < res.size(); k++)
tmp.push_back(res[k]+chars[j]);


这句是解题关键,字符串容器res存的是每遍历一个号码后所有的组合可能。每读一个号码对应的字母,就将其依次放到res中每个字符串的尾部,存入临时变量tmp,直到该号码对应的所有字母遍历完,将tmp赋值给res。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值