# 对以下字符进行压缩编码
更多描述
这是一道大厂常考的代码题
- Input: 'aaaabbbccd'
- Output: 'a4b3c2d1',代表 a 连续出现四次,b连续出现三次,c连续出现两次,d连续出现一次
Issue
欢迎在 Issue 中交流与讨论: Issue 419 (opens new window)
Author
编写函数 encode
实现该功能
function encode (str) {
const l = []
let i = 0
for (const s of str) {
const len = l.length
const lastChar = len > 0 ? l[len - 1][0] : undefined
if (lastChar === s) {
l[len - 1][1]++
} else {
l.push([s, 1])
}
}
return l.map(x => x.join('')).join('')
}
测试通过
> encode('aaab')
< "a3b1"
但是面试官往往会继续深入
- 如果只出现一次,不编码数字,如
aaab -> a3b
- 如果只出现两次,不进行编码,如
aabbb -> aab3
- 如果进行解码