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

来源:互联网 发布:javascript let var 编辑:程序博客网 时间:2024/06/05 14:11

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。

0 0