一、題目
給定一個字符串 s 和一些長度相同的單詞 words。找出 s 中恰好可以由 words 中所有單詞串聯(lián)形成的子串的起始位置。
注意子串要與 words 中的單詞完全匹配,中間不能有其他字符,但不需要考慮 words 中單詞串聯(lián)的順序。
示例 1:
輸入:
s = "barfoothefoobarman",
words = ["foo","bar"]
輸出:[0,9]
解釋:
從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。
示例 2:
輸入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
輸出:[]
二、題解
題目 :給定一個字符串 s 和一些長度相同的單詞 words。
題目解讀:
參數(shù)一個String類型的數(shù)組,一個字符串
words的每個長度都相等。
數(shù)組中的幾個值任意組合,然后在字符串中找到對應(yīng)的下標(biāo)。
返回一個下標(biāo)組成的list
解體方法
- 用一個map記錄words中的單詞各有多少個
- 每個word的單詞長度為len,所有單詞的總長度allLen
- s中依次截取allLen的字符串,然后以len長度分割單詞,每個單詞記錄到tempMap中
- 比較map和Map是不是相等
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new LinkedList<Integer>();//用來記錄結(jié)果
Map<String, Integer> map = new HashMap<String,Integer>();//用來記錄words中的每個單詞,以及單詞的長度
if(words.length==0||s==null||"".equals(s))return result;//基礎(chǔ)判斷
int len = words[0].length();//每個單詞的長度
int allLen = len*words.length;//所有單詞拼接起來的總長度
if(s.length()<allLen)return result;
for(int i=0;i<words.length;i++) {
map.put(words[i],map.getOrDefault(words[i], 0)+1);
}
//
for(int i=0;i<s.length()-allLen+1;i++) {//s中依次截取allLen的字符串
Map<String, Integer> tempMap = new HashMap<String,Integer>();
for(int j =0;j<allLen;j+=len) {//截取每個單詞
String tempWrod = s.substring(i+j,i+j+len);
tempMap.put(tempWrod,tempMap.getOrDefault(tempWrod, 0)+1);//單詞進(jìn)入map
}
if(map.equals(tempMap)){result.add(i);}//
}
return result;
}
}