您的位置:首页 > 产品设计 > UI/UE

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

2016-01-20 23:38 387 查看
求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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: