Open harrytothemoon opened 3 years ago
直覺暴力解
var decodeString = function(s) {
let countStack = [0]
let strStack = ['']
let index = 0
while (index < s.length) {
let temp = ''
if (s[index] === ']') {
// 遇到 ],往回加入重複字串
let str = strStack.pop()
strStack[strStack.length - 1] += str.repeat(countStack.pop())
index++
} else if (isNaN(s[index])) {
// 遇到字母,取完所有字母
while(isNaN(s[index]) && s[index] !== ']' && index < s.length) {
temp += s[index]
index++
}
if (strStack.length === countStack.length) {
strStack[strStack.length - 1] += temp
} else {
strStack.push(temp)
}
} else if (!isNaN(s[index])) {
// 遇到數字,取完所有數字
while(!isNaN(s[index])) {
temp += s[index]
index++
}
countStack.push(Number(temp))
if (!isNaN(s[index + 1])) strStack.push('')
// 跳過 [
index++
}
}
return strStack[0]
};
另類的雙指針
var decodeString = function(s) {
while (s.indexOf('[') !== -1) {
let left = s.lastIndexOf('[')
let right = left + s.substring(left).indexOf(']')
let str = s.substring(left + 1, right)
// 拼數字
let count = ''
while (s[left-1] <= 9) {
left--
count = s[left] + count
}
s = s.substring(0, left) + str.repeat(count) + s.substring(right + 1) // right 是第二次迴圈開始會用到
}
return s
};
/**
* @param {string} s
* @return {string}
*/
var decodeString = function(s) {
let num = 0
let res = ''
let stack = []
for(let char of s) {
if(char === '[') {
stack.push(res)
stack.push(num)
res = ''
num = 0
} else if(char === ']') {
const preNum = stack.pop()
const preStr = stack.pop()
res = preStr + res.repeat(preNum)
} else if(char >= '0' && char <= '9') {
num = num * 10 + Number(char)
} else if(char >= 'a' && char <= 'z') {
res += char
}
}
return res
};
暴力解法
另一種覺得比較直觀的方法