forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationinString.js
More file actions
Latest commit
58 lines (54 loc) · 1.74 KB
/
Copy pathPermutationinString.js
File metadata and controls
58 lines (54 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @name The-Sliding-Window Algorithm is primarily used for the problems dealing with linear data structures like Arrays, Lists, Strings etc.
* These problems can easily be solved using Brute Force techniques which result in quadratic or exponential time complexity.
* Sliding window technique reduces the required time to linear O(n).
* @see [The-Sliding-Window](https://www.geeksforgeeks.org/window-sliding-technique/)
*/
/**
* @function PermutationinString
* @description Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
* @param {String} s1 - The input string
* @param {String} s2 - The input string
* @return {boolean} - Returns true if s2 contains a permutation of s1, or false otherwise.
*/
exportfunctionPermutationinString(s1,s2){
if(s1.length>s2.length)returnfalse
letstart=0
letend=s1.length-1
consts1Set=SetHash()
consts2Set=SetHash()
for(leti=0;i<s1.length;i++){
s1Set[s1[i]]++
s2Set[s2[i]]++
}
if(equals(s1Set,s2Set))returntrue
while(end<s2.length-1){
if(equals(s1Set,s2Set))returntrue
end++
constc1=s2[start]
constc2=s2[end]
if(s2Set[c1]>0)s2Set[c1]--
s2Set[c2]++
start++
if(equals(s1Set,s2Set))returntrue
}
returnfalse
}
functionequals(a,b){
returnJSON.stringify(a)===JSON.stringify(b)
}
functionSetHash(){
constset=newSet()
constalphabets='abcdefghijklmnopqrstuvwxyz'
for(leti=0;i<alphabets.length;i++){
set[alphabets[i]]=0
}
returnset
}
// Example 1:
// Input: s1 = "ab", s2 = "eidbaooo"
// Output: true
// Explanation: s2 contains one permutation of s1 ("ba").
// Example 2:
// Input: s1 = "ab", s2 = "eidboaoo"
// Output: false