题解——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
- 题解——Leetcode 17.Letter Combinations of a Phone Number 难度:Medium
- LeetCode题解——Letter Combinations of a Phone Number
- Leetcode 17. Letter Combinations of a Phone Number (Medium) (cpp)
- 17. Letter Combinations of a Phone Number LeetCode题解
- Leetcode题解-17. Letter Combinations of a Phone Number
- LeetCode——17. Letter Combinations of a Phone Number
- Leetcode——17. Letter Combinations of a Phone Number
- LeetCode刷题(C++)——Letter Combinations of a Phone Number(Medium)
- <LeetCode><Medium>17Letter Combinations of a Phone Number
- 【Medium】17. Letter Combinations of a Phone Number
- 17. Letter Combinations of a Phone Number -Medium
- 17. Letter Combinations of a Phone Number Medium
- LeetCode题解:Letter Combinations of a Phone Number
- leetcode 题解 || Letter Combinations of a Phone Number 问题
- LeetCode 题解(77): Letter Combinations of a Phone Number
- LeetCode题解:Letter Combinations of a Phone Number
- 【leetcode题解】【M】【67】Letter Combinations of a Phone Number
- LEETCODE 17 Letter Combinations of a Phone Number (JAVA题解)
- EasyUI使用心得——datagrid的条件查询,过滤
- 【ArcGIS 10.5 产品白皮书】第一章 走近ArcGIS平台1
- oracle id自增相关问题
- 基于openfire+smack的Android、Web、PC开发
- 递推递归练习D
- 题解——Leetcode 17.Letter Combinations of a Phone Number 难度:Medium
- docker registry接入ceph Swift API
- 网易编程题六,最大的奇约数(递推计算)
- AS使用过程中的那些坑
- Python转义符
- PDF文字替换
- 编程面试:排序(一)
- 容器OCI规范 镜像规范
- JavaScript瀑布流的实现以及底部刷新