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 }