Alibaba筆試題:
給定一段產品的英文描述,包含M個英文字母,每個英文單詞以空格分隔,無其他標點符號;再給定N個英文單詞關鍵字,請說明思路並編程實現方法String extractSummary(String description,String[] keywords),目標是找出此產品描述中包含N個關鍵字(每個關鍵詞至少出現一次)的長度最短的子串,作為產品簡介輸出。
這個問題和編程之美3.5的題目類似,就是在字串description中找一段包含keywords數組中所有字串關鍵字的字串。
思路:利用兩個索引分別指向我們最終產生的摘要的位置,接下來進行如下迴圈:(1)首先判斷摘要中是否包含所有關鍵字,如果不全包括,則將遍曆的尾標誌向後加1,直到包含所有關鍵字都被包含或者尾標誌超出範圍。(2)接下來將遍曆的首標誌向後移動,並不斷檢查移動過程中摘要是否還是全部被包含,如果被全部包含,說明存在長度更小的摘要,這時需要更新最短摘要的長度及下標位置;如果再移動過程中發現不全部包含了,則繼續(1)的操作,直到尾標誌超出範圍。
演算法實現如下所示:
package com.part3;import java.util.Map;import java.util.HashMap;//最短摘要產生public class Abstract {private int[] keywordsCount;//記錄關鍵字被訪問的次數private int pstart=0,pend=0;//定義尋找起始點和終點private int astart=0,aend=0;//定義摘要起始點和終點private int abstractlen=0;//摘要長度private Map<String,Integer> map;//定義關鍵字到訪問次數的映射public Abstract(String[] keywords){int len=keywords.length;keywordsCount=new int[len];map=keywordsMap(keywords);}public String extractSummary(String source,String[] keywords){String[] src=source.split(" ");return extract(src,keywords);}public String extract(String[] source,String[] keywords){int len=source.length;abstractlen=len+1;while(true){while(!isAllExisted()&&pend<len){if(this.map.get(source[pend])!=null){setKeywordsCount(this.map.get(source[pend]),false);}pend++;}while(isAllExisted()){if(pend-pstart<abstractlen){abstractlen=pend-pstart;astart=pstart;aend=pend-1;}if(this.map.get(source[pstart])!=null){setKeywordsCount(this.map.get(source[pstart]),true);}pstart++;}if(pend>=len)break;}StringBuilder summary=new StringBuilder();for(int i=astart;i<aend;i++){summary.append(source[i]+" ");}summary.append(source[aend]);return summary.toString();}private Map<String,Integer> keywordsMap(String[] keywords)//將關鍵字和其索引構成映射關係{Map<String,Integer> map=new HashMap<String,Integer>();int len=keywords.length;for(int i=0;i<len;i++){map.put(keywords[i], i);}return map;}private void setKeywordsCount(int i,boolean flag)//flag為false時次數減1,為true時次數加1{if(flag)this.keywordsCount[i]++;elsethis.keywordsCount[i]--;}private boolean isAllExisted()//判斷關鍵字是否都包含{boolean res=true;for(int count:keywordsCount){if(count==0){res=false;break;}}return res;}//測試案例public static void main(String[] args) {// TODO Auto-generated method stubString description="hello software hello test world spring sun world flower hello"; String[] keywords = {"sun","flower"}; Abstract nAbstract = new Abstract(keywords); System.out.println(nAbstract.extractSummary(description, keywords));}}
代碼測試結果如下所示:
sun world flower
運行結果滿足題意,既包含所有關鍵字,長度也最短。