LeetCode 30. 與所有單詞相關聯的字串 Substring with Concatenation of All Words
阿新 • • 發佈:2019-02-17
給定一個字串 s 和一些長度相同的單詞 words。在 s 中找出可以恰好串聯 words 中所有單詞的子串的起始位置。
注意子串要與 words 中的單詞完全匹配,中間不能有其他字元,但不需要考慮 words 中單詞串聯的順序。
示例 1:
輸入: s = "barfoothefoobarman", words = ["foo","bar"] 輸出:
[0,9]
解釋: 從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。
示例 2:
輸入: s = "wordgoodstudentgoodword", words = ["word","student"] 輸出:
[]
public class Solution { public List<Integer> findSubstring(String s, String[] words) { ArrayList<Integer> ret=new ArrayList<Integer>(); if ( s==null || words==null || words.length==0 ) { return ret; } HashMap<String,Integer> maps=new HashMap<String,Integer>(); for(int i=0;i<words.length;i++){ if ( maps.containsKey(words[i]) ){ int t = maps.get(words[i]); maps.put(words[i], t+1); }else{ maps.put(words[i],1); } } int wordLength=words[0].length(); for(int i=0;i<wordLength;i++){ HashMap<String,Integer> need =new HashMap<String,Integer>(maps); int start=i,end=i; int needCnt=words.length; if ( (s.length()-start)< (wordLength*needCnt)) { break; } for(;end<s.length();end+=wordLength){ if ( s.length()-end < wordLength ) { break; } String tmp= s.substring(end,end+wordLength); if (maps.containsKey(tmp)){ int t=need.get(tmp); need.put(tmp,t-1); if ( t>0) { needCnt--; } } if ( needCnt==0 ){ while(true){ String toRemove=s.substring(start,start+wordLength); if (maps.containsKey(toRemove) ){ int t =need.get(toRemove); if ( t <0 ){ need.put(toRemove,t+1); } else break; } start+=wordLength; } if (end-start == wordLength*(words.length-1)) { ret.add(start); } } } } return ret; } }