注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
本帖最后由 美帝马甲 于 2021-7-15 22:30 编辑
leetcode 17变种
原题是一个字符,map 一个数组中任意一个字符
变种是:多个字符,map一个string
map.put("1","abc");
map.put("2","bcd");
map.put("3","def");
map.put("4","gg");
map.put("12","yy");
map.put("23","dx");
map.put("34","gwew");
map.put("234","wsgvw");
给“1234”,输入各种可能的组合
我个code: 直接套用word breakII
拿到组合的list后
遍历每个组合,再map到value, 感觉这个太土了,有没有更好的解法
code 先贴上- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- public class LetterCombinationsofaPhoneNumber_2 {
- public List<String> letterCombinations_valuesAreString(String s) {
- HashMap<String,String > map = new HashMap<String, String>();
- map.put("1","abc");
- map.put("2","bcd");
- map.put("3","def");
- map.put("4","gg");
- map.put("12","yy");
- map.put("23","dx");
- map.put("34","gwew");
- map.put("234","wsgvw");
- List<String> keys=new ArrayList<>();
- for(String key: map.keySet())
- keys.add(key);
- List<String> combinationList = new ArrayList<String>();
- combinationList=DFS(s, keys,new HashMap<String, List<String>> ());
- List<String> res=new ArrayList<>();
- for(String combination:combinationList){
- StringBuilder sb=new StringBuilder();
- String[] strs=combination.split(" ");
- for(String str:strs)
- sb.append(map.get(str));
- res.add(sb.toString());
- System.out.println();
- }
- return res;
- }
- public List<String> DFS(String s, List<String> wordDict,
- HashMap<String, List<String>> memory){
- if(s.length()==0)
- return Arrays.asList(new String[]{""});
- if(memory.containsKey(s))
- return memory.get(s);
- List<String> res = new ArrayList<>();
- for(String word : wordDict){
- if(s.startsWith(word)){
- for(String postfix : DFS(s.substring(word.length()),
- wordDict,memory)){
- if(postfix.length()==0){
- res.add(word);
- }else{
- res.add(word + " " + postfix);
- }
- }
- }
- }
- memory.put(s, res);
- return memory.get(s);
- }
- public static void main(String [] args){
- LetterCombinationsofaPhoneNumber_2 test=new LetterCombinationsofaPhoneNumber_2();
- List<String> res=test.letterCombinations_valuesAreString("1234");
- System.out.print(res);
- }
复制代码
|