Skip to content

Commit e2225fc

Browse files
committed
feat: Solve permutation in string
- Leetcode, #567
1 parent 013d2ab commit e2225fc

File tree

2 files changed

+66
-5
lines changed

2 files changed

+66
-5
lines changed

minimum-diff-sum.js

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,10 @@ function findMinimumDiff(arr, remaining, accrued, size, maxSize) {
1111
findMinimumDiff([...arr, n], cloneArr, accrued + n, size + 1, maxSize);
1212
});
1313
}
14-
if (arr.length > 0) {
15-
min = Math.min(
16-
Math.abs(accrued - remaining.reduce((a, b) => a + b, 0)), min
17-
);
18-
}
14+
if (arr.length > 0) {
15+
min = Math.min(
16+
Math.abs(accrued - remaining.reduce((a, b) => a + b, 0)), min
17+
);
1918
}
2019
var min = Infinity;
2120
findMinimumDiff([], A, 0, 1, A.length - 1);

permutation-in-string.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Leetcode, #567
3+
* Given two strings s1 and s2, write a function to return true if s2 contains
4+
* the permutation of s1. In other words, one of the first string's
5+
* permutations is the substring of the second string.
6+
*
7+
* Constraints:
8+
* 1. The input strings only contain lower case letters.
9+
* 2. The length of both given strings is in range [1, 10,000].
10+
*/
11+
12+
/**
13+
* @param {string} s1
14+
* @param {string} s2
15+
* @return {boolean}
16+
*/
17+
function checkInclusion(s1, s2) {
18+
const regex = new RegExp(`[${s1}]`);
19+
if (!s1 || !s2) {
20+
return false;
21+
}
22+
if (s1.length > s2.length) {
23+
return false;
24+
}
25+
if (!s2.match(regex)) {
26+
return false;
27+
}
28+
const map = new Map();
29+
s1.split('').forEach(ch => {
30+
map.set(ch, map.has(ch) ? map.get(ch) + 1 : 1);
31+
});
32+
const windowMap = new Map();
33+
let matched = 0;
34+
let l = 0;
35+
let r = 0;
36+
while (r < s2.length && l <= r) {
37+
let lastLetter = s2.substr(r, 1);
38+
windowMap.set(lastLetter, windowMap.has(lastLetter) ? windowMap.get(lastLetter) + 1 : 1);
39+
if (map.has(lastLetter)) {
40+
if (map.get(lastLetter) === windowMap.get(lastLetter)) {
41+
matched++;
42+
if (matched === map.size) {
43+
return true;
44+
}
45+
} else if (windowMap.get(lastLetter) > map.get(lastLetter)) {
46+
let letter = s2.substr(l, 1);
47+
windowMap.set(letter, windowMap.get(letter) - 1);
48+
if (map.has(letter) && map.get(letter) - windowMap.get(letter) === 1) {
49+
matched--;
50+
}
51+
l++;
52+
}
53+
r++;
54+
} else {
55+
r++;
56+
l = r;
57+
matched = 0;
58+
windowMap.clear();
59+
}
60+
}
61+
return false;
62+
};

0 commit comments

Comments
 (0)