Skip to content

Commit 8f5595b

Browse files
authored
Update 2060-check-if-an-original-string-exists-given-two-encoded-strings.js
1 parent 839e609 commit 8f5595b

File tree

1 file changed

+67
-2
lines changed

1 file changed

+67
-2
lines changed

2060-check-if-an-original-string-exists-given-two-encoded-strings.js

Lines changed: 67 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,68 @@
1+
/**
2+
* @param {string} s1
3+
* @param {string} s2
4+
* @return {boolean}
5+
*/
6+
const possiblyEquals = function(s1, s2) {
7+
const n = s1.length
8+
const m = s2.length
9+
const memo = Array.from({ length: n + 1 }, () =>
10+
Array.from({ length: m + 1 }, () => Array(1001).fill(null))
11+
)
12+
memo[0][0][1000] = true
13+
14+
return dfs(0, 0, 0)
15+
16+
function dfs(i, j, diff) {
17+
if(memo[i][j][diff] != null) return memo[i][j][diff]
18+
let res = false
19+
if (i == n && j == m) res = diff === 0
20+
else if (i < n && isDigit(s1[i])) {
21+
let ii = i
22+
while (ii < n && isDigit( s1[ii] )) ii += 1
23+
for (let x of helper(s1.slice(i, ii))) {
24+
if (dfs(ii, j, diff-x)) res = true
25+
}
26+
} else if (j < m && isDigit( s2[j] )) {
27+
let jj = j
28+
while (jj < m && isDigit( s2[jj] )) jj += 1
29+
for (let y of helper(s2.slice(j, jj))) {
30+
if (dfs(i, jj, diff+y)) res = true
31+
}
32+
} else if (diff == 0) {
33+
if (i < n && j < m && s1[i] == s2[j]) res = dfs(i+1, j+1, 0)
34+
} else if (diff > 0) {
35+
if (i < n) res = dfs(i+1, j, diff-1)
36+
} else {
37+
if (j < m) res = dfs(i, j+1, diff+1)
38+
}
39+
40+
memo[i][j][diff] = res
41+
return res
42+
}
43+
44+
function isDigit(ch) {
45+
return ch >= '0' && ch <= '9'
46+
}
47+
48+
function helper(str) {
49+
const ans = new Set()
50+
ans.add(+str)
51+
for(let i = 1, len = str.length; i < len; i++) {
52+
const pre = helper(str.slice(0, i))
53+
const post = helper(str.slice(i))
54+
for(let p of pre) {
55+
for(let n of post) {
56+
ans.add(p + n)
57+
}
58+
}
59+
}
60+
return Array.from(ans)
61+
}
62+
};
63+
64+
// another
65+
166
/**
267
* @param {string} s1
368
* @param {string} s2
@@ -6,8 +71,8 @@
671
var possiblyEquals = function (s1, s2) {
772
let n = s1.length
873
let m = s2.length
9-
const f = Array.from({ length: 41 }, () =>
10-
Array.from({ length: 41 }, () => Array(1001).fill(false))
74+
const f = Array.from({ length: n + 1 }, () =>
75+
Array.from({ length: m + 1 }, () => Array(1001).fill(false))
1176
)
1277
f[0][0][1000] = true
1378

0 commit comments

Comments
 (0)