2Sigma OA prepare: Longest Chain

DP use HashMap:

根据string的长度sort,然后维护每个string的longest chain,default为1,如果删除某个char生成的string能提供更长的chain,则更新

 1 package twoSigma;
 2 
 3 import java.util.Arrays;
 4 import java.util.Comparator;
 5 import java.util.HashMap;
 6 import java.lang.StringBuilder;
 7 
 8 public class LongestChain {
 9     public int findLongestChain(String[] words) {
10         if (words==null || words.length==0) return 0;
11         int longestChain = 0;
12         Arrays.sort(words, new Comparator<String>() {
13             public int compare(String str1, String str2) {
14                 return str1.length()-str2.length();
15             }
16         });
17         HashMap<String, Integer> map = new HashMap<String, Integer>();
18         for (String word : words) {
19             if (map.containsKey(word)) continue;
20             map.put(word, 1);
21             for (int i=0; i<word.length(); i++) {
22                 StringBuilder sb = new StringBuilder(word);
23                 sb.deleteCharAt(i);
24                 String after = sb.toString();
25                 if (map.containsKey(after) && map.get(after)+1 > map.get(word)) {
26                     map.put(word, map.get(after)+1);
27                 }
28             }
29             if (map.get(word) > longestChain) longestChain = map.get(word);
30         }
31         return longestChain;
32     }
33 
34     /**
35      * @param args
36      */
37     public static void main(String[] args) {
38         // TODO Auto-generated method stub
39         LongestChain sol = new LongestChain();
40         //String[] words = new String[]{"6", "a", "b", "ba", "bca", "bda", "bdca"};
41         //String[] words = new String[]{"a", "a", "bc", "exf", "abc"};
42         String[] words = new String[]{"bc", "abc"};
43         int longestChain = sol.findLongestChain(words);
44         System.out.println(longestChain);
45     }
46 
47 }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值