add: 字符串解码

This commit is contained in:
yi-ge 2020-05-28 06:31:10 +08:00
parent a69362984c
commit 95ca64dc6c
3 changed files with 48 additions and 0 deletions

View File

@ -369,6 +369,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 155. 最小栈 <https://leetcode-cn.com/problems/min-stack/>
- LintCode 12. 带最小值操作的栈 <https://www.lintcode.com/problem/min-stack/description>
- [字符串解码](src/stack/decode-string.js)
- LeetCode 394. 字符串解码 <https://leetcode-cn.com/problems/decode-string/>
- LintCode 575. 字符串解码 <https://www.lintcode.com/problem/decode-string/description>
## 数学
- [阶乘后的零](src/math/factorial-trailing-zeroes.js)

View File

@ -0,0 +1,36 @@
// s = "3[a]2[bc]", 返回 "aaabcbc".
// s = "3[a2[c]]", 返回 "accaccacc".
// s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
/**
* @param {string} s
* @return {string}
*/
export const decodeString = function (s) {
const stack = []
let multiple = ''
for (let i = 0, len = s.length; i < len; i++) {
if (!isNaN(Number(s[i]))) { // 判断是数字
if (i === 0 || !isNaN(Number(s[i - 1]))) { // 如果上一位也是数字,则
multiple += s[i]
} else {
multiple = s[i]
}
} else if (multiple && s[i] === '[') {
stack.push(Number(multiple))
multiple = ''
} else if (s[i] === ']') {
let current = stack.pop()
let tmpStr = ''
while (typeof current !== 'number') {
tmpStr = current + tmpStr
current = stack.pop()
}
tmpStr = tmpStr.repeat(current)
stack.push(tmpStr)
} else {
stack.push(s[i])
}
}
return stack.join('')
}

View File

@ -0,0 +1,7 @@
import { decodeString } from '../../src/stack/decode-string'
test('字符串解码', () => {
expect(decodeString('3[a]2[bc]')).toBe('aaabcbc')
expect(decodeString('3[a2[c]]')).toBe('accaccacc')
expect(decodeString('2[abc]3[cd]ef')).toBe('abcabccdcdcdef')
})