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表示不存在

 package ShortestSubsequenceIncluding;

 public class Solution {

       public String findShortest(String a, String b){
if(a==null || b==null || a.length()==0 || b.length()==0) throw new IllegalArgumentException(); int lena = a.length(), lenb = b.length();
int[][] dp = new int[lenb][lena]; for(int i=0; i<lenb; i++){
char bc = b.charAt(i);
for(int j=0; j<lena; j++){
char ac = a.charAt(j);
dp[i][j] = Integer.MAX_VALUE; if(ac==bc){
if(i==0) dp[i][j] = 1;
else {
for (int t = 0; t < j; t++) {
if (dp[i - 1][t] == Integer.MAX_VALUE) continue;
else dp[i][j] = Math.min(dp[i][j], dp[i - 1][t] + j - t);
}
}
}
}
} int min = Integer.MAX_VALUE;
int end = -1; for(int j=0; j<lena; j++){
if(dp[lenb-1][j] < min) {
min = dp[lenb-1][j];
end = j;
}
} if(end==-1) return "no match!";
return a.substring(end-min+1, end+1);
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution sol = new Solution();
String res = sol.findShortest("acbacbc", "abc");
System.out.println(res); } }
上一篇:python类、对象、方法、属性之类与对象笔记


下一篇:python 类、对象、方法、属性