標籤:
題目描述:
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]
You should return the indices: [0,9].
(order does not matter).
解題思路:
首先設定一個HashMap,裡面索引值為單詞,元素值為對應單詞出現的次數,將其作為比較的模板。
我們首先在一個大的迴圈裡面獲得字串的第一個位置開始的第一個單詞,查看上述的模板Map中是否存在這個單詞。如果不存在,那麼外面的大迴圈直接後移一位,匹配下一個位置開始的單詞。同時內嵌迴圈,用於逐個單詞進行排查。如果尋找是存在的,那麼我們把這個單詞加入到新的Map中,同時統計次數也需要遞增。接下來查看這個新Map中的該單詞出現的次數是否小於的個等於模板中該單詞出現的次數,如果大於該次數,說明情況是不符合要求的,跳出該內層迴圈,外層迴圈的指標後移。
最後如果內層迴圈如果順利走完,則說明從該位置開始所有的單詞都是匹配的,那麼將該位置添加到List中,否則外層迴圈指標指向下一個字元的外置,繼續開始類似的判斷。
代碼如下:
public class Solution { public List<Integer> findSubstring(String s, String[] words) {List<Integer> list = new ArrayList<Integer>();Map<String, Integer> map = new HashMap<String, Integer>();Map<String, Integer> tmp = new HashMap<String, Integer>();int sLength = s.length();int wordsNum = words.length;int wordsLength = words[0].length();int j;if (sLength < wordsNum || wordsNum == 0)return list;for (int i = 0; i < wordsNum; i++) {if (map.containsKey(words[i]))map.put(words[i], map.get(words[i]) + 1);elsemap.put(words[i], 1);}for (int i = 0; i <= sLength - wordsNum * wordsLength; i++) {tmp.clear();for (j = 0; j < wordsNum; j++) {String word = s.substring(i + j * wordsLength, i + j* wordsLength + wordsLength);if (!map.containsKey(word))break;if (tmp.containsKey(word))tmp.put(word, tmp.get(word) + 1);elsetmp.put(word, 1);if (tmp.get(word) > map.get(word))break;}if (j == wordsNum)list.add(i);}return list;}}
Java [leetcode 30]Substring with Concatenation of All Words