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); } }
相关文章推荐
- iOS UITableView(十四) 设置TbleviewController的滚动范围
- android tv-Building TV Games
- com.android.tools.build:gradle:2.0.0-alpha3 build errors
- Android BLE与终端通信(二)——Android Bluetooth基础科普以及搜索蓝牙设备显示列表
- Android BLE与终端通信(二)——Android Bluetooth基础搜索蓝牙设备显示列表
- Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptabl
- UITableView Group类型扁平化适配iOS6.0
- Android BLE与终端通信(一)——Android Bluetooth基础API以及简单使用获取本地蓝牙名称地址
- Android BLE与终端通信(一)——Android Bluetooth基础API以及简单使用获取本地蓝牙名称地址
- 简述UIViewControl之间的七种传值方式
- request \response 总结
- 【慕课笔记】第四章 流程控制语句 第10节 JAVA循环跳转语句之continue
- servlet 之request
- LeetCode 225 Implement Stack using Queues(用队列来实现栈)(*)
- mui中文在线手册及教程文档
- HDU1242 Rescue(BFS松弛)
- C#queue队列总结
- LeetCode 232 Implement Queue using Stacks(用栈来实现队列)(*)
- HBuilder mui引导页制作
- HBuilder教程