17. Letter Combinations of a Phone Number
来源:互联网 发布:天天卡牌淘宝杂货铺 编辑:程序博客网 时间:2024/05/29 09:21
题目:Letter Combinations of a Phone Number
原题链接:https://leetcode.com/problems/letter-combinations-of-a-phone-number/
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”].
给出一个数字串,返回在9宫格键盘上所有可能的字母组合。
如图,按下23,则有可能出现的组合有[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].
看这个电话键盘可以发现,除了2到9之外的按键都是没有字母的,所以第一步我们可以把其他多余的字符都剔除掉,假设得到的字符串为temp。
然后采用回溯的方法。
由于temp的长度已知,我们就可以确定结果中字母串的长度,这样可以预先分配好空间,假设我们用字符串 s 来存放临时的结果。
设一个cnt[10000]数组。其中cnt[ i ]表示当前数字temp[ i ]所对应的字母的下标。一旦下标到达上限,我们就把下标置0,并且让i - 1,回到上一个数字重新开始选择。
当i == temp.length()时,就是一个可能的结果,存起来。
当回溯到 i == -1时,回溯结束。
代码如下:
class Solution {public: vector<string> letterCombinations(string digits) { vector<string> ans; string num[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; string temp, ret; int len = digits.length(); for(int i = 0; i < len; ++i) { if(digits[i] >= '2' && digits[i] <= '9') temp += digits[i]; } len = temp.length(); if(len == 0) return ans; int cnt[10000] = {0}; int i = 0, j = 0; string s; s.resize(len); while(i >= 0) { if(i == len) { ans.push_back(s); i--; }else if(cnt[i] == num[temp[i] - '0'].length()){ cnt[i] = 0; i--; }else{ s[i] = num[temp[i] - '0'][cnt[i]]; cnt[i]++; i++; } } return ans; }};
- 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
- 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
- 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
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number
- Spring Boot全局支持CORS(跨源请求)的配置方法
- 1_7生成窗口最大值数组
- 解决-打开eclipse时出现“Failed to load the JNI shared library”的问题
- Android非常好用的相册开源项目-TelegramGallery
- 修改apt-get和yum为阿里源
- 17. Letter Combinations of a Phone Number
- webstorm搭配Monokai-Sublime主题颜色方法
- Android/Socket使用
- 42-带参数的信号
- 实现vector的代码
- 【中文分词系列】 5. 基于语言模型的无监督分词
- 弹出框
- python--删除文本中的空行
- NGINX基本操作