Created
September 1, 2020 07:57
-
-
Save ufo22940268/6c8277176f3b7cdbbfc41d6134abeac1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let count = (s) => { | |
| return Array(s.length) | |
| .fill(0) | |
| .reduce((accu, _, i) => { | |
| const c = s[i]; | |
| if (!accu[c]) { | |
| accu[c] = 1; | |
| } else { | |
| accu[c] += 1; | |
| } | |
| return accu; | |
| }, {}); | |
| }; | |
| function canShift(cs, ct, c) { | |
| let c1 = cs[c] || 0; | |
| let c2 = ct[c] || 0; | |
| if (c2 === 0) { | |
| return true; | |
| } else { | |
| return c1 > c2; | |
| } | |
| } | |
| function subCharCount(obj, c) { | |
| let o = Object.assign({}, obj); | |
| o[c] = o[c] - 1; | |
| return o; | |
| } | |
| function minWindowForSubString(s, cs, ct, start, end) { | |
| // let s1 = s.substr(start, end - start + 1); | |
| let minL = null; | |
| if (canShift(cs, ct, s[start])) { | |
| minL = minWindowForSubString(s, subCharCount(cs, s[start]), ct, start + 1, end); | |
| } | |
| let minR = null; | |
| if (canShift(cs, ct, s[end])) { | |
| minR = minWindowForSubString(s, subCharCount(cs, s[end]), ct, start, end - 1); | |
| } | |
| let cur = [start, end]; | |
| let r = [cur, minL, minR].filter(t => !!t); | |
| r.sort((l, r) => { | |
| return (l[1] - l[0]) - (r[1] - r[0]); | |
| }); | |
| return r && r[0]; | |
| } | |
| let minWindow = (s, t) => { | |
| let cs = count(s); | |
| let ct = count(t); | |
| let start = 0; | |
| let end = s.length - 1; | |
| if (!Object.keys(ct) | |
| .every(key => | |
| ct[key] <= (cs[key] || 0) | |
| )) { | |
| return ''; | |
| } | |
| let range = minWindowForSubString(s, cs, ct, start, end); | |
| if (!range) { | |
| return ''; | |
| } else { | |
| return s.substr(range[0], range[1] - range[0] + 1); | |
| } | |
| }; | |
| // let r = minWindow('cabwefgewcwaefgcf', 'cae'); | |
| // let r = minWindow('a', 'aa'); | |
| // let r = minWindow('ab', 'a'); | |
| // let r = minWindow('ADOBECODEBANC', 'ABC'); | |
| console.log('r: ' + JSON.stringify(r, null, 4) + '\n'); | |
| // let k = count('cabwefgewcwaefgcf'); | |
| // console.log('k: ' + JSON.stringify(k, null, 4) + '\n'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment