这个题经过了转化之后得题意就变成了找出给定字符串数组中匹配关键字的最短的距离。
这个题的方法首先是遍历一遍数组,找到匹配关键字的第一个字的序号,然后向后找到第一次全部匹配的位置,求出这一个完整的匹配的大小,退出循环。
然后将第一个字的序号向后移一位再次进行匹配,这样的好处在于可以让关键字已任意顺序进行匹配,而且这样能够减少对数组的遍历次数(以往的遍历都是需要再遍历一次从而确定第二次的起始位置的)。
具体代码如下:
package test; public class ShortestAbstract{ boolean first=false; int start=-1; String [] abstracts={"a","b"}; public void shortest(String a[]){ int min = 999; while(start<a.length){ int temp = isAllExisted(a,start+1); if(temp==999){ break; } if(temp<min){ min = temp; } } System.out.println("mins is "+min); } private int isAllExisted(String [] a ,int begin){ boolean [] abs = new boolean[abstracts.length]; int count=0; int abBegin = begin; boolean first = false; for(int i=begin;i<a.length;i++){ for(int j=0;j<abstracts.length;j++){ if((abstracts[j].equals(a[i]))&& !abs[j]){ if(!first){ first = true; abBegin = i; } abs[j]= true; for(int k=0;k<abs.length;k++){ if(!abs[k]){ count++; } } if(count==0){ //将下一次搜索得起始点定在当前第一个找到的点得后一个点上 start = abBegin; return (i-abBegin)+1; } } } count = 0; } return 999; } public static void main(String [] args){ String [] a ={"c","d","e","f","a","t","f","b","a","e","b"}; ShortestAbstract sa = new ShortestAbstract(); sa.shortest(a); } }