Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 37b2ceb

Browse files
Merge pull request TheAlgorithms#715 from Koddi-Evangelista/master
feat: add scramble string algorithm
2 parents 9aedaa8 + 9d996e1 commit 37b2ceb

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎String/ScrambleStrings.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Problem Statement and Explanation: https://leetcode.com/problems/scramble-string/
2+
3+
/**
4+
* Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
5+
* @param {string} s1
6+
* @param {string} s2
7+
* @return {boolean}
8+
*/
9+
10+
const isScramble = (s1, s2) => {
11+
return helper({}, s1, s2)
12+
}
13+
14+
const helper = function (dp, s1, s2) {
15+
const map = {}
16+
17+
if (dp[s1 + s2] !== undefined) return dp[s1 + s2]
18+
if (s1 === s2) return true
19+
20+
for (let j = 0; j < s1.length; j++) {
21+
if (map[s1[j]] === undefined) map[s1[j]] = 0
22+
if (map[s2[j]] === undefined) map[s2[j]] = 0
23+
map[s1[j]]++
24+
map[s2[j]]--
25+
}
26+
27+
for (const key in map) {
28+
if (map[key] !== 0) {
29+
dp[s1 + s2] = false
30+
return false
31+
}
32+
}
33+
34+
for (let i = 1; i < s1.length; i++) {
35+
if (
36+
(helper(dp, s1.substr(0, i), s2.substr(0, i)) &&
37+
helper(dp, s1.substr(i), s2.substr(i))) ||
38+
(helper(dp, s1.substr(0, i), s2.substr(s2.length - i)) &&
39+
helper(dp, s1.substr(i), s2.substr(0, s2.length - i)))
40+
) {
41+
dp[s1 + s2] = true
42+
return true
43+
}
44+
}
45+
46+
dp[s1 + s2] = false
47+
return false
48+
}
49+
50+
console.log(isScramble('great', 'rgeat'))

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /