• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

G面经prepare: Maximum Subsequence in Another String's Order

求string str1中含有string str2 order的 subsequence 的最小长度

DP做法:dp[i][j]定义为pattern对应到i位置,string对应到j位置时,shortest substring的长度,Int_Max表示不存在

 1 package ShortestSubsequenceIncluding;
 2 
 3 public class Solution {
 4     
 5       public String findShortest(String a, String b){
 6             if(a==null || b==null || a.length()==0 || b.length()==0) throw new IllegalArgumentException();
 7 
 8             int lena = a.length(), lenb = b.length();
 9             int[][] dp = new int[lenb][lena];
10 
11             for(int i=0; i<lenb; i++){
12                 char bc = b.charAt(i);
13                 for(int j=0; j<lena; j++){
14                     char ac = a.charAt(j);
15                     dp[i][j] = Integer.MAX_VALUE;
16 
17                     if(ac==bc){
18                         if(i==0) dp[i][j] = 1;
19                         else {
20                             for (int t = 0; t < j; t++) {
21                                 if (dp[i - 1][t] == Integer.MAX_VALUE) continue;
22                                 else dp[i][j] = Math.min(dp[i][j], dp[i - 1][t] + j - t);
23                             }
24                         }
25                     }
26                 }
27             }
28 
29             int min = Integer.MAX_VALUE;
30             int end = -1;
31 
32             for(int j=0; j<lena; j++){
33                 if(dp[lenb-1][j] < min) {
34                     min = dp[lenb-1][j];
35                     end = j;
36                 }
37             }
38 
39 
40             if(end==-1) return "no match!";
41             return a.substring(end-min+1, end+1);
42     }
43     
44 
45     /**
46      * @param args
47      */
48     public static void main(String[] args) {
49         // TODO Auto-generated method stub
50         Solution sol =  new Solution();
51         String res = sol.findShortest("acbacbc", "abc");
52         System.out.println(res);
53 
54     }
55 
56 }

 

posted @ 2016-01-20 23:38  neverlandly  阅读(350)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3