leetcode之路017 Letter Combinations of a Phone Number


题目大意:给定一个数字的字符串,返回所有的有数字代表的字母组合。


例:

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
思路:

1、用一个字符串数组表示每个数字代表的字母,对输入的第一个数字,直接将此数字代表的所有字母加入到结果resu中;

2、对于以后的每一个数字,设此数字代表的字母串为temp,将temp的每一个字母加到当前的resu中每一个string的后面即可。

例:”232“,第一步:将第一个数字代表的字母a,b,c加入到resu中,得到{”a“,”b“,”c“}。

第二步:将3所代表的字母temp为d,e,f,分别添加到resu的每个string后面,具体实现是,对于temp中temp.length()-1到1的元素”c“,"b",直接在resu最后添加新项"a"+f,"b"+f,"c"+f,"a"+e,"b"+e,"c"+e,对于temp中下标为0的元素,直接resu中的0-2元素后面接上d即可,这样不用新建空间,直接在resu中操作。

下面是ac的代码,运行时间0ms:

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> resu;
		vector<string> map;
		map.push_back("abc");map.push_back("def");map.push_back("ghi");map.push_back("jkl");//对照表
		map.push_back("mno");map.push_back("pqrs");map.push_back("tuv");map.push_back("wxyz");
		int prv_size=0;
        for(int i=0;i<digits.length();++i)
		{
			int index=digits[i]-'0';
			string temp=map[index-2];
			if(i==0)
			{
				for(int j=0;j<temp.length();++j)  //处理第一个数字
				{
					char ch[2];<span style="white-space:pre">	//此处需要注意,不能直接用resu.push_back(temp[j]);
					ch[0]=temp[j];   //因为resu中是字符串,rtemp[j]是字符。
					ch[1]='\0';<span style="white-space:pre">	//因此进行了转换
					resu.push_back(ch);
				}	
			}
			else
			{
				prv_size=resu.size();
				for(int j=map[index-2].length()-1;j>=0;--j)
				{
					if(j!=0)
					{
						for(int k=0;k<prv_size;++k)
						{
							resu.push_back(resu[k]+temp[j]);
						}
					}
					if(j==0)  
					{
						for(int k=0;k<prv_size;++k)
						{
							resu[k]=resu[k]+temp[j];
						}
					}	
				}
			}
			
		}
		return resu;
    }
};

不过也是不够简洁,因此在for没有使用额外的空间来保存结果。如果使用vertor<string>来保存结果,代码可以大大减少,因为上述代码的两个if语句都可以合并一起考虑,代码如下:

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






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值