刷题17. Letter Combinations of a Phone Number
Posted siweihz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷题17. Letter Combinations of a Phone Number相关的知识,希望对你有一定的参考价值。
一、题目说明
题目17. Letter Combinations of a Phone Number,题目给了下面一个图,输入一个字符串包括2-9,输出所有可能的字符组合。
如输入23
所有可能的输出:
"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"
二、我的做法
这个题目,我思考了4个小时(惭愧严重超时了),做法如下:
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
class Solution{
public:
vector<string> letterCombinations(string s){
vector<string> res;
if(s.size()<1) return res;
int num = 1;
unordered_map<char,string> ump;
ump['2'] = "abc";
ump['3'] = "def";
ump['4'] = "ghi";
ump['5'] = "jkl";
ump['6'] = "mno";
ump['7'] = "pqrs";
ump['8'] = "tuv";
ump['9'] = "wxyz";
for(int i=0;i<s.size();i++){
switch(s[i]){
case '2':
case '3':
case '4':
case '5':
case '6':
case '8':
num *= 3;
break;
case '7':
case '9':
num *=4;
break;
}
}
for(int i=0;i<num;i++){
res.push_back("");
}
int curNum = num;
for(int j=0;j<s.size();++j){
char curr = s[j];
string curStr = ump[curr];
curNum /= curStr.size();
for(int i=0;i<num;i++){
res[i].push_back(curStr[i / curNum % curStr.size()]);
}
}
return res;
}
};
int main(){
Solution s;
// vector<string> r = s.letterCombinations("234");
// for(vector<string>::iterator it=r.begin();it!=r.end();++it){
// cout<<*it<<" ";
// }
// cout<<endl;
vector<string> r = s.letterCombinations("8");
for(vector<string>::iterator it=r.begin();it!=r.end();++it){
cout<<*it<<" ";
}
return 0;
}
这个是我第一次,做“完美”的代码。臭美一下!
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Letter Combinations of a Phone Number.
Memory Usage: 8.4 MB, less than 100.00% of C++ online submissions for Letter Combinations of a Phone Number.
三、更优化的做法
第一次可以自豪的说一句,这个就是最优化的代码了。哈哈!
以上是关于刷题17. Letter Combinations of a Phone Number的主要内容,如果未能解决你的问题,请参考以下文章
17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number