偶遇算法-字符串的解压缩
Opened this issue · 0 comments
chunhuigao commented
题目
有一种简易压缩算法:针对全部为小写英文字母组成的字符串, 将其中连续超过两个相同字母的部分压缩为连续个数加该字母 其他部分保持原样不变. 例如字符串 aaabbccccd 经过压缩变成字符串 3abb4cd
请您编写解压函数,根据输入的字符串,判断其是否为合法压缩过的字符串。
若输入合法则输出解压缩后的字符串,否则输出字符串"!error"来报告错误。
输入描述:
输入一行,为一个ASCII字符串
长度不超过100字符
用例保证输出的字符串长度也不会超过100字符
输出描述:
若判断输入为合法的经过压缩后的字符串
则输出压缩前的字符串
若输入不合法 则输出字符串"!error"
示例 1:
输入:4dff
输出: ddddff
解释:4d扩展为4个d ,故解压后的字符串为ddddff
示例 2:
输入:2dff
输出: !error
解释:2个d不需要压缩 故输入不合法
示例 3:
输入:4d@A
输出: !error
解释:全部由小写英文字母组成的字符串,压缩后不会出现特殊字符@和大写字母A 故输入不合法
代码
function decode(s) {
const reg = new RegExp(/(\w)\1{2}/g);
if (reg.test(s)) {
console.log('!error');
} else {
const len = s.length;
let num = 0;
let string = '';
const list = [];
let result = null;
for (let i = 0; i < len; i++) {
const c = s[i];
if (isDigit(c) || isAlp(c)) {
if (isDigit(c)) {
if (string) {
list.push([1, string]);
}
num = num * 10 + Number(c);
string = '';
} else {
string += c;
if (num === 0) {
} else if (num < 3) {
result = '!error';
break;
} else {
if (i < len - 1) {
if (c === s[i + 1]) {
result = '!error';
break;
}
}
list.push([num, string]);
string = '';
}
num = 0;
}
} else {
result = '!error';
break;
}
}
if (result) {
console.log(result);
} else {
if (num > 0) {
console.log('!error');
} else {
if (string) {
list.push([1, string]);
}
let r = '';
list.forEach((v) => {
const [n, s] = v;
r += s.repeat(n);
});
console.log(r);
}
}
}
function isAlp(s) {
const n = s.charCodeAt() - 'a'.charCodeAt();
return n >= 0 && n <= 26;
}
function isDigit(s) {
const n = s.charCodeAt() - '0'.charCodeAt();
return n >= 0 && n <= 9;
}
}
const testList = ['4dff', '2dff', '4d@A', '5a', '3a4b'];
testList.forEach((v) => {
decode(v);
});