1. 程式人生 > >Leetcode 30.與所有單詞相關聯的子串

Leetcode 30.與所有單詞相關聯的子串

與所有單詞相關聯的字串

給定一個字串 和一些長度相同的單詞 words。 s 中找出可以恰好串聯 words 中所有單詞的子串的起始位置。

注意子串要與 words 中的單詞完全匹配,中間不能有其他字元,但不需要考慮 words 中單詞串聯的順序。

示例 1:

輸入:

s = "barfoothefoobarman",

words = ["foo","bar"]

輸出: [0,9]

解釋: 從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" 。

輸出的順序不重要, [9,0] 也是有效答案。

 

題目的意思是給你一個字串,和一個字串的陣列,需要返回一個該字串的索引組成的陣列,返回的索引有如下性質:從每個索引開始,長度為L的字串需要精確包含字串陣列中的所有字串(不多不少)。L 為字串陣列中所有字串長度之和。

解決思路,使用一個map,鍵為字串陣列中的字串,值為該字串在字串陣列中出現的次數。遍歷字串s,尋找和字串陣列中的字串相同的字串,找到後map中的值減一,否則重新初始化map,從下一個字元開始遍歷。如果map中所有的值都為0,則找到了一個符合條件的子串,索引壓入陣列。

 1 import java.util.ArrayList;
 2 import java.util.HashMap;
3 import java.util.List; 4 5 class Solution { 6 public static void initializeMap(HashMap<String,Integer> hashMap, String[] words){ 7 //hashMap=new HashMap<String,Integer>(); 8 for(int i=0;i<words.length;i++){ 9 if(!hashMap.containsKey(words[i])){
10 hashMap.put(words[i],1); 11 }else{ 12 hashMap.put(words[i],hashMap.get(words[i])+1); 13 } 14 } 15 } 16 public static List<Integer> findSubstring(String s, String[] words) { 17 if(s==null || s.equals("") || words.length==0) return new ArrayList<Integer>(); 18 HashMap<String,Integer> hashMap=new HashMap<String,Integer>(); 19 int singleWordLen=words[0].length();//單個字串長度 20 int wordsLen=words.length; 21 int slen=s.length(); 22 int i,j,count; 23 boolean countChange=false;//判斷是否改變過map中的值,如果沒有變則無需重新初始化 24 List<Integer> result=new ArrayList<Integer>(); 25 count=wordsLen;//計數器表示還需要找到的字串個數 26 if(wordsLen==0 || slen==0) return result; 27 initializeMap(hashMap,words); 28 for(i=0;i<=slen-wordsLen*singleWordLen;i++){ 29 String subStr=s.substring(i,i+singleWordLen); 30 j=i; 31 //當該字串存在於map中且值大於0,並且j不越界的情況下 32 while(hashMap.containsKey(subStr) && hashMap.get(subStr)!=0 && j+singleWordLen<=slen){ 33 hashMap.put(subStr,hashMap.get(subStr)-1); 34 count--; 35 countChange=true;//改變了map的值 36 j=j+singleWordLen; 37 if(j+singleWordLen<=slen) 38 subStr=s.substring(j,j+singleWordLen);//下一個字串 39 else 40 break; 41 if(!hashMap.containsKey(subStr)) 42 break; 43 } 44 if(count==0){ 45 result.add(i);//找齊所有字串陣列中的字串後把該索引壓入 46 } 47 if(countChange){ 48 hashMap.clear(); 49 initializeMap(hashMap,words); 50 count=wordsLen; 51 countChange=false; 52 } 53 } 54 return result; 55 } 56 57 public static void main(String[] args){ 58 String s="wordgoodgoodgoodbestword"; 59 String[] words={"word","good","best","good"}; 60 List<Integer> list=findSubstring(s,words); 61 for(int i:list){ 62 System.out.println(i); 63 } 64 } 65 }