Skip to content

Commit 40c0421

Browse files
committed
Add solution #567
1 parent 9a1a02a commit 40c0421

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@
118118
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|
119119
565|[Array Nesting](./0565-array-nesting.js)|Medium|
120120
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
121+
567|[Permutation in String](./0567-permutation-in-string.js)|Medium|
121122
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
122123
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
123124
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 567. Permutation in String
3+
* https://leetcode.com/problems/permutation-in-string/
4+
* Difficulty: Medium
5+
*
6+
* Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
7+
*
8+
* In other words, return true if one of s1's permutations is the substring of s2.
9+
*/
10+
11+
/**
12+
* @param {string} s1
13+
* @param {string} s2
14+
* @return {boolean}
15+
*/
16+
var checkInclusion = function(s1, s2) {
17+
const getCharCode = c => c.charCodeAt() - 'a'.charCodeAt();
18+
const isMatch = (a1, a2) => a1.every((n, i) => a2[i] === n);
19+
20+
if (s1.length > s2.length) {
21+
return false;
22+
}
23+
24+
const map1 = new Array(26).fill(0);
25+
const map2 = new Array(26).fill(0);
26+
for (let i = 0; i < s1.length; i++) {
27+
map1[getCharCode(s1[i])]++;
28+
map2[getCharCode(s2[i])]++;
29+
}
30+
31+
for (let i = 0; i < s2.length - s1.length; i++) {
32+
if (isMatch(map1, map2)) return true;
33+
map2[getCharCode(s2[i + s1.length])]++;
34+
map2[getCharCode(s2[i])]--;
35+
}
36+
37+
return isMatch(map1, map2);
38+
};

0 commit comments

Comments
 (0)