題目描述:
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.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
Output: []
代碼解答:
package com.jack.algorithm;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* create by jack 2018/11/6
*
* @author jack
* @date: 2018/11/6 22:11
* @Description:
*/
public class SubstringWithConcatenationOfAllWords {
/**
* 題目描述:
* https://leetcode.com/problems/substring-with-concatenation-of-all-words/
*
* @param s
* @param words
* @return
*/
public static List<Integer> findSubstring(String s, String[] words){
List<Integer> indexes = new ArrayList<>();
//字符串s和單詞數組的邊界詞判斷,符合條件直接返回
if (words == null || s == null || words.length == 0) {
return indexes;
}
//記錄單詞出現次數的集合
final Map<String, Integer> counts = new HashMap<>();
for (final String word : words) {
//getOrDefault方法如果存在這個key,則返回value,否則返回默認值
counts.put(word, counts.getOrDefault(word, 0) + 1);
}
//n表示字符串s的長度,num表示單詞數組的長度,len表示每個單詞的長度
final int n = s.length(), num = words.length, len = words[0].length();
//i表示循環次數,最外層循環的次數
for (int i = 0; i < n - num * len + 1; i++) {
final Map<String, Integer> seen = new HashMap<>();
int j = 0;
while (j < num) {
//截取字符串s的子串
final String word = s.substring(i + j * len, i + (j + 1) * len);
//判斷截取的子串是否在單詞數組中,如果存在,則進入if判斷裏面,否則結束循環
if (counts.containsKey(word)) {
seen.put(word, seen.getOrDefault(word, 0) + 1);
//如果單詞不夠,說明不能完全匹配,結束循環
if (seen.get(word) > counts.getOrDefault(word, 0)) {
break;
}
} else {
//不包含直接結束
break;
}
j++;
}
//如果所有的單詞都在s串中,則記錄這個下標
if (j == num) {
indexes.add(i);
}
}
return indexes;
}
public static void main(String[] args) {
//String s = "barfoothefoobarman";
//String s = "wordgoodgoodgoodbestword";
String s = "aaa";
//String[] words = {"foo","bar"};
//String[] words = {"word","good","best","word"};
String[] words = {"a","a"};
//String[] words = {"1","2","3","4"};
//System.out.println(JSONObject.toJSONString(words));
//displayAllStr(words, 0, 3);
List<Integer> rs = findSubstring(s,words);
System.out.println("結果爲:"+JSONObject.toJSONString(rs));
}
}
源碼地址: