串聯(lián)所有單詞的子串

題目描述:給定一個字符串?s?和一些長度相同的單詞?words。找出 s 中恰好可以由?words 中所有單詞串聯(lián)形成的子串的起始位置。

注意子串要與?words 中的單詞完全匹配,中間不能有其他字符,但不需要考慮?words?中單詞串聯(lián)的順序。

示例:輸入:

? s = "barfoothefoobarman",

? words = ["foo","bar"]

輸出:[0,9]

解釋:

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

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

java代碼

class Solution {

? ? public List<Integer> findSubstring(String s, String[] words) {

? ? ? ? List<Integer> res = new ArrayList<Integer>();

? ? ? ? int wordNum = words.length;

? ? ? ? if(wordNum == 0) return res;

? ? ? ? int wordLen = words[0].length();

? ? ? ? //HashMap1存所有單詞

? ? ? ? HashMap<String,Integer> allWords = new HashMap<String,Integer>();

? ? ? ? for(String w:words) {

? ? ? ? ? ? int value = allWords.getOrDefault(w,0);

? ? ? ? ? ? allWords.put(w,value+1);

? ? ? ? }

? ? ? ? //遍歷所有子串

? ? ? ? for(int i=0;i<s.length()-wordNum*wordLen+1;i++) {

? ? ? ? ? ? //HshMap2存當(dāng)前掃描的字符串含有的單詞

? ? ? ? ? ? HashMap<String,Integer> hasWords = new HashMap<String,Integer>();

? ? ? ? ? ? int num = 0;

? ? ? ? ? ? while(num < wordNum) {

? ? ? ? ? ? ? ? String word = s.substring(i + num*wordLen,i+(num+1)*wordLen);

? ? ? ? ? ? ? ? //判斷該單詞是否在HashMap1中

? ? ? ? ? ? ? ? if(allWords.containsKey(word)) {

? ? ? ? ? ? ? ? ? ? int value = hasWords.getOrDefault(word,0);

? ? ? ? ? ? ? ? ? ? hasWords.put(word,value+1);

? ? ? ? ? ? ? ? ? ? //判斷當(dāng)前單詞的value和HashMap1中該單詞的value

? ? ? ? ? ? ? ? ? ? if(hasWords.get(word) > allWords.get(word)) {

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }else {

? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? num++;

? ? ? ? ? ? }

? ? ? ? ? ? if(num == wordNum) {

? ? ? ? ? ? ? ? res.add(i);

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return res;

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容