LeetCode 30. Substring with Concatenation of All Words
Description
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
Code
- java
import java.util.HashSet;
import java.util.HashMap;
import java.util.Map;
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
List<Integer> result = new ArrayList<>();
if(s.length() == 0 || words.length == 0) return result;
int maxL = 0, minL = Integer.MAX_VALUE;
int len = 0;
for(String word : words) {
len += word.length();
maxL = Math.max(maxL, word.length());
minL = Math.min(minL, word.length());
}
boolean[] vis = new boolean[words.length];
for(int i = 0; i <= s.length()-len; i++) {
String str = s.substring(i, i + len);
boolean match = true;
for(String word : words) {
if(str.indexOf(word) == -1) {
match = false;
break;
}
}
if(match) {
for(int j = 0; j < str.length(); ) {
match = false;
for(int l = maxL; l>=minL; l--) {
String tem = str.substring(j, j+l);
for(int k = 0; k < words.length; k++) {
if(!vis[k] && words[k].equals(tem)) {
vis[k] = true;
match = true;
j += l;
break;
}
}
if(match) break;
}
if(!match) break;
}
if(match) {
for(int j = 0; j < words.length; j++) {
if(!vis[j]) {
match = false;
break;
}
}
if(match) result.add(i);
}
vis = new boolean[words.length];
}
}
return result;
}
}
- Others’ Soulution
- java
class Solution {
public List<Integer> findSubstring(String s, String[] words) {
final Map<String, Integer> counts = new HashMap<>();
for (final String word : words) {
counts.put(word, counts.getOrDefault(word, 0) + 1);
}
final List<Integer> indexes = new ArrayList<>();
if(words.length == 0) return indexes;
final int n = s.length(), num = words.length, len = words[0].length();
for (int i = 0; i < n - num * len + 1; i++) {
final Map<String, Integer> seen = new HashMap<>();
int j = 0;
while (j < num) {
final String word = s.substring(i + j * len, i + (j + 1) * len);
if (counts.containsKey(word)) {
seen.put(word, seen.getOrDefault(word, 0) + 1);
if (seen.get(word) > counts.getOrDefault(word, 0)) {
break;
}
} else {
break;
}
j++;
}
if (j == num) {
indexes.add(i);
}
}
return indexes;
}
}
Conclusion
- 忽略了题目中words数组的word长度一样的条件
- 没有用HashMap,我是弟弟
- HashMap.getOrDefault(Object obj, Object defaultValue)
- HashMap.put(Object key, Object value)
- HashMap.containsKey(Object key)