Substring with Concatenation of All Words

来源:互联网 发布:spss论文数据分析教程 编辑:程序博客网 时间:2024/06/03 08:49

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

You should return the indices: [0,9].

题中要求将S中包含由L中所有word组成的字串时 返回其起始位置,关键问题在于 确保L中的词语 必用且仅用一次 这个作为判断的标准 显然 适合用哈希表来做 将L存在哈希表中 利用哈希表的查找依次删除已经匹配长度的S字符串中包含的词语 若最后表为空 则即为所求

public class Solution {    public List findSubstring(String S, String[] L) {       int len=S.length();       int step=L[0].length();       int num=L.length;       HashMap hm=new HashMap();       for(String s:L){           if(hm.containsKey(s)){               hm.put(s,hm.get(s)+1);           }else{               hm.put(s,1);           }       }       List res=new ArrayList();       for(int i=0;i+step*num<=len;i++){           int fw=i;           HashMap com=new HashMap(hm);           while(true){               String word=S.substring(fw,fw+step);               if(com.containsKey(word)){                   if(com.get(word)==1){                       com.remove(word);                   }else{                       com.put(word,com.get(word)-1);                   }                   if(com.isEmpty()){                       res.add(i);                       break;                   }                   fw=fw+step;               }else{                   break;               }           }       }       return res;          }}


一开始使用暴力求解法 也能得到答案 但时间复杂度不达要求

public static List findSubstring(String S,String[] L){  List list=new ArrayList();        int num=L.length;        int len=S.length();        int step=L[0].length();        if(len  for (int i = 0; i + step * num <=len; i++) {            String ss=S.substring(i,i+step*num);   String com = S.substring(i, i + step);   for (int j = 0; j < num;j++) {    if (L[j].equals(com)){     boolean a=judge(ss,L);     if(a==true)list.add(i);     break;    }   }  }  return list;  }public static boolean judge(String S,String[] L){  boolean a=true;  String[] cur=new String[L.length];  int curc=0;   int num=L.length;      int len=S.length();      int step=L[0].length();      int [] inds=new int[num];      int flag=1;  for(int i=0;i   String com = S.substring(i, i + step);   if(a==false) break;   int cc=curc;   for (int j = 0; j < num; j++) {    for(int k=0;k     if(j==inds[k]){      //a=false;      //break;      flag=0;     }    }if(flag==0){     flag=1;    }else    if (L[j].equals(com)){          inds[curc]=j;     curc++;     break;    }       }    if(cc==curc){    a=false;    break;   }  }  return a;  }



0 0
原创粉丝点击