You are given a string s and an array of strings words. All the strings of words are of the same length.
A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated.
- For example, if
words = ["ab","cd","ef"], then"abcdef","abefcd","cdabef","cdefab","efabcd", and"efcdab"are all concatenated strings."acdbef"is not a concatenated string because it is not the concatenation of any permutation ofwords.
Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.
Example 1:
Input:s = "barfoothefoobarman"words = ["foo", "bar"]
Output: [0,9]
Explanation:
The substring starting at 0 is "barfoo". It is the concatenation of ["bar","foo"] which is a permutation of words.
The substring starting at 9 is "foobar". It is the concatenation of ["foo","bar"] which is a permutation of words.
Example 2:
Input:s = "wordgoodgoodgoodbestword"words = ["word", "good", "best", "word"]
Output: []
Explanation:
There is no concatenated substring.
Example 3:
Input:s = "barfoofoobarthefoobarman"words = ["bar", "foo", "the"]
Output: [6,9,12]
Explanation:
The substring starting at 6 is "foobarthe". It is the concatenation of ["foo","bar","the"].
The substring starting at 9 is "barthefoo". It is the concatenation of ["bar","the","foo"].
The substring starting at 12 is "thefoobar". It is the concatenation of ["the","foo","bar"].
Constraints:
1 <= s.length <= 1041 <= words.length <= 50001 <= words[i].length <= 30sandwords[i]consist of lowercase English letters.
哦,这道题,一开始是理解错了题目意思了。
仔细研读要求。是对每一个substring,例如从0 开始的,还有从9开始的substring(长度为L的总长度), 里面包含了L里的所有的non-intervening 组合。就是把所有的L的string连起来。
例如,上面例子中从0 开始的: barfoo 就是L的一个组合。 同样,从9开始的,foobar 也是一个组合。
假设L 里一共有n个string,每个string 长度为 m
分析:
1:我们不能穷尽L的组合形式。 2^n
2: 我们如果从每一个节点都开始计算L, 有点儿太啰嗦的感觉。 想想有没有什么好方法,来跳过部分预先监测的结果。
3: NOTE: strings in L, might exist replication.
4: 初步设想,用一个 list 记录所有match 的节点。然后看后面的substring是否match。 这样,问题就归结于该list里面的值,是否能凑够0到n-1个match。--------但这里有个问题,就是L中 可能有重复的情况。需要注意对待。
(问题就归结到,一个list,每个点包含了match的位置,如果全部的,都有0到n-1都能match的话,就加入result中,否则 移动到下一个点。)
from collections import defaultdictclass Solution:def findSubstring(self, s: str, words: List[str]) -> List[int]:m, n = len(words), len(words[0])orig_M = defaultdict(int)for word in words:orig_M[word] += 1def remove1(cur_M: defaultdict, key: str):cur_M[key] -= 1if not cur_M[key]:cur_M.pop(key)res = []for offset in range(n):new_M = defaultdict(int)M = orig_M.copy()start, end = offset, offsetwhile start + m*n <= len(s):if end + n > len(s):# go beyond sstart = len(s) #breakend += nnew_word = s[end-n:end]if new_word not in M:if new_word not in new_M: # never find, resetM = orig_M.copy()new_M.clear()start = endelse: # find in the new_M, thus go backend -= n# shrink first word on leftfirst_word = s[start: start+n]start += nremove1(new_M, first_word)M[first_word] += 1elif new_word in M:new_M[new_word] += 1remove1(M, new_word)if not M:res.append(start)# shrink first word on leftfirst_word = s[start: start+n]start += nremove1(new_M, first_word)M[first_word] += 1return res
------------------------------4th pass----------------------------
思路: 因为允许重复,所以要记录下出现的次数,因此需要用HashMap.
而这次,为了加速,我们在最外边的循环中,用了 基于各个起始点的位置。
public class Solution {
public List<Integer> findSubstring(String S, String[] L) {
List<Integer> list = new LinkedList<Integer>();
if(S==null || L == null | S.length()==0 || L.length == 0)
return list;
// note that L might contains duplicates
int n = S.length(), m = L[0].length(), k = L.length;
HashMap<String, Integer> origMap = new HashMap<String,Integer>();
for(int i= 0;i<L.length;i++){
String str = L[i];
int count = 1;
if( origMap.containsKey(str)){
count += origMap.get(str);
}
origMap.put(str,count);
}
for(int i =0;i<m;i++){ // for each possible starting position
HashMap<String,Integer> tmpMap = new HashMap<String, Integer>();
int j = i;
while( j<= n-m ){
// remove the oldest
if( j-m*k>=0 ){
String oldStr = S.substring(j-m*k,j-m*k+m);
if(tmpMap.containsKey(oldStr)){
if(tmpMap.get(oldStr)>1){
tmpMap.put(oldStr,tmpMap.get(oldStr)-1);
}else{
tmpMap.remove(oldStr);
}
}
}
// add the newest
String newStr = S.substring(j,j+m);
int nFind = 1;
if(tmpMap.containsKey(newStr)){
nFind += tmpMap.get(newStr);
}
tmpMap.put(newStr,nFind);
// check if it is match
boolean isAllFind = true;
for(String str : origMap.keySet()){
if(tmpMap.containsKey(str)== false || tmpMap.get(str)!=origMap.get(str)){
isAllFind = false;
break;
}
}
if(isAllFind)
list.add(j-m*k+m);
//update j
j+=m;
}
}
return list;
}
}
--------------------第二遍----------- AC 了 --------
思路就是: 既然允许有重复, 而且, 还要尽量快, 用Set是不太行了。 那就用HashMap, 来记录下 每个key的出现的次数。
public class Solution {
public ArrayList<Integer> findSubstring(String S, String[] L) {
ArrayList<Integer> al = new ArrayList<Integer>();
if (S == null || L == null || S.length() == 0 || L.length == 0)
return al;
// make a set from L, so that we can
int nL = L.length;
int mL = L[0].length();
for (int k = 0; k <= S.length() - nL * mL; k++) {
Map<String, Integer> map = buildSet(L);
String curS = S.substring(k, k + mL * nL);
int i = 0;
int matchedCount = 0;
while (matchedCount < nL) {
String tmp = curS.substring(i, i + mL);
if (map.containsKey(tmp)) {
int count = map.get(tmp);
if(count <=0)
break;
map.put(tmp, count - 1);
i += mL;
matchedCount++;
} else
break;
}
// iterator all the list, to see whether it has been fully visited
boolean isAllFind = true;
for(String key : map.keySet())
if(map.get(key)>0){
isAllFind = false;
break;
}
if(isAllFind)
al.add(k);
}
return al;
}
private Map<String, Integer> buildSet(String[] L) {
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < L.length; i++) {
if (map.containsKey(L[i])) {
int count = map.get(L[i]);
map.put(L[i], count + 1);
} else
map.put(L[i], 1);
}
return map;
}
}
Mistakes:
----------------第二遍------开始理解错题意了。
1: 所谓的withougt any interleaving characters,是指一个 concatenation里面不能interleaving. 但是,多个,是可以的。
2: 输入的 L 可以是["a","b","a"] , 因此,不能用Set 来存储。
Learned:
---------------3 rd 想利用每个L 中的 string 映射到一个HashMap上去。------------
思想很简单, 和楼上的那个通不过的方法如出一致。-------------其实就是第二遍的思想。-------
就是对每个string in L ,map 一个数值。 作为标记。 然后,看其是否在map中出现过,如果出现过,对比出现的次数。
但是,还是suffer了这样一个问题, 就是L 中有重复的情况。
因此,我们还需要记录在L中出现的次数。 作为参照物,还要记录用过的次数。
因此,我们自己定义了一个类。
public class Solution {
public ArrayList<Integer> findSubstring(String S, String[] L) {
ArrayList<Integer> al = new ArrayList<Integer>();
int n = L.length;// assume n > 0
int l = L[0].length();
HashMap<String, SNode> map = new HashMap<String, SNode>();
int nDifferent=0; // number of different Strings in L
for(int i =0;i< n;i++){
SNode node = map.get(L[i]);
if(node == null){
nDifferent++;
node = new SNode(nDifferent);
map.put(L[i],node);
}else
node.count++;
}
// for each position, calculate its total sum
for(int i =0;i<= S.length() - l*n; i++){
for(int j =0;j< n;j++) // reset all
map.get(L[j]).nUsed=0;
// test sum of these String
boolean isBreak = false;
for(int k = 0;k<n;k++){
String str= S.substring(i+k*l, i+(k+1)*l);
SNode node = map.get(str);
if(node == null || node.nUsed>=node.count){
isBreak = true;
break;
}else{
node.nUsed++;
}
}
if(!isBreak)
al.add(i);
}
return al;
}
}
class SNode{
public int val;
public int count;
public int nUsed=0; // number of used
public SNode(int v){
val = v;
count = 1;
}
}
No comments:
Post a Comment