public class ShortDigest {
private HashMap<String, Integer> map = new HashMap<String, Integer>();
//保存最短摘要的起始和结束位置。
private Point shortest = new Point();
public ShortDigest(String[] keys){
for(String key : keys){
map.put(key, 0);
}
}
public String getShortDigest(String[] ss){
assert(true);
updateShortest(ss, 0, 0);
int i = shortest.x;
int j = shortest.y;
String result = "";
for(int k=i; k<=j; k++){
result += ss[k] + " ";
}
return result;
}
/**
* 两个指针,代表头尾, 先移动尾指针至满足要求,再移动头指针,缩小范围。
* 然后递归至结束。
* @param ss
* @param start
* @param end
*/
private void updateShortest(String[] ss, int start, int end){
int i = start;
int j = end;
if(j >= ss.length-1){
return;
}
while(!isAllKeys()){
j++;
if(j==ss.length){
return;
}
if(isKey(ss[j])){
map.put(ss[j], map.get(ss[j])+1);
}
}
while(isAllKeys()){
if(isKey(ss[i])){
map.put(ss[i], map.get(ss[i])-1);
}
i++;
}
int current = j-i+2;
if((shortest.length==0) || (shortest.length>current)){
shortest.set(i-1, j);
}
updateShortest(ss, i, j);
}
private boolean isAllKeys(){
for(String key : map.keySet()){
int v = map.get(key);
if(v == 0){
return false;
}
}
return true;
}
public boolean isKey(String s){
return map.containsKey(s);
}
public class Point{
public int x;
public int y;
public int length;
public void set(int x, int y){
this.x = x;
this.y = y;
length = y-x+1;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "Online retailer book of book movies music and games item along with electronics toys book apparel " +
"sports tools of groceries and general home and garden item";
String[] ss = s.split("\\s");
String[] keys = {"book", "item", "of"};
ShortDigest sd = new ShortDigest(keys);
String res = sd.getShortDigest(ss);
System.out.println(res);
}
}
最短摘要
最新推荐文章于 2021-07-29 09:32:49 发布