我有一个关于运行长度编码的字符串面试问题,我的解决方案是 O(n)。有什么办法可以改进:
const firstString=(str)=>{
const arr = str.split('');
let counter = 1;
let result ='';
for (let i=0; i<arr.length; i++){
if(arr[i] === arr[i+1]){
counter++;
} else {
result +=arr[i]+counter;
counter = 1;
}
} return result
};
firstString('AABBBCAAEE');
将此方法与正则 表达式一起使用:正则表达式匹配/分组字符串中的重复字符
正则表达式解释: /((.)\2*)/g
var str = 'AABBBCAAEE';
var result = str.replace(/((.)\2*)/g, function(match) {
var [letter] = match;
return `${letter}${match.length}`;
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句