给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例:
输入:“23”
输出:[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
求解:
#include <iostream> // std::cin, std::cout
#include <queue> // std::queue
#include<map>
using namespace std;
vector<string> letterCombinations(string digits) {
vector<string> res;//用于输出向量
map<char, string> m = { {'2',"abc" },{'3',"def"},{'4',"ghi"},{'5',"jkl"},{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"} };//映射map哈希表
int size = digits.size();//输入字符串产长度
queue<string> que;//新建队列
//先将第一个元素对应的码表入队
for (int j = 0; j < m[digits[0]].size(); j++)
{
string str;
str.push_back(m[digits[0]][j]);//char转string
que.push(str);//string入队
}
string s;//用于存储队头元素
for (int i = 1; i < size; i++)
{
int length = que.size();//当前队列长度
while (length--)
{
for (int j = 0; j < m[digits[i]].size(); j++)
{
s = que.front();
s = s + m[digits[i]][j];//队头元素加上新元素
que.push(s);//入队
}
que.pop();//队头出队
}
}
while (!que.empty())
{
res.push_back(que.front());//队头元素存储至res
que.pop();//队头出队
}
return res;//返回
}
int main ()
{
string s="23";
vector<string> str=letterCombinations(s);
for(auto k:str)
{
cout<<k<<" ";
}
return 0;
}