Skip to content

Commit 00c248c

Browse files
authored
Merge pull request #681 from shankr4444/shankr4444-patch-1
Added Solution for LeetCode Problem No. 30
2 parents e2fd54e + 5d6da24 commit 00c248c

File tree

1 file changed

+61
-0
lines changed
  • LeetCode/30. Substring with Concatenation of All Words

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// https://leetcode.com/problems/substring-with-concatenation-of-all-words/
2+
3+
class Solution
4+
{
5+
public List<Integer> findSubstring(String s, String[] words)
6+
{
7+
if(words[0].length()*words.length>s.length())
8+
return new ArrayList<>();
9+
10+
Map<String,Integer> word_frq=new HashMap<>();
11+
List<Integer> ans=new ArrayList<>();
12+
13+
// Map store the frequency of every word in words[]
14+
15+
for(String str:words)
16+
word_frq.put(str,word_frq.getOrDefault(str,0)+1);
17+
18+
int wordlen=words[0].length();
19+
20+
String[] str=new String[s.length()];
21+
22+
for(int i=0;i<wordlen;i++)
23+
{
24+
Map<String,Integer> frq=new HashMap<>(); // count frequency of words inside the window
25+
26+
int begin=i,size=0; // size is the no. of window and begin is the starting index of window
27+
28+
// s.length()-wordlen -> based on observation
29+
30+
for(int j=i;j<=s.length()-wordlen;j+=wordlen)
31+
{
32+
str[j]=s.substring(j,j+wordlen); // window
33+
if(word_frq.containsKey(str[j]))
34+
{
35+
begin= begin==-1? j:begin; // begin=-1 means new window need to be started
36+
frq.put(str[j],frq.getOrDefault(str[j],0)+1);
37+
size++;
38+
39+
if(size==words.length) // substring may be possible
40+
{
41+
if(frq.equals(word_frq))
42+
ans.add(begin);
43+
44+
// sliding the window
45+
46+
frq.put(str[begin],frq.get(str[begin])-1);
47+
begin+=wordlen; // new starting index
48+
size--;
49+
}
50+
}
51+
else // reset window
52+
{
53+
begin=-1;
54+
size=0;
55+
frq.clear();
56+
}
57+
}
58+
}
59+
return ans;
60+
}
61+
}

0 commit comments

Comments
 (0)