Javascript 压缩字符串的算法
我想写一个函数来压缩字符串的字符,比如'bbbab'将被转换成'b3ab',我被卡住了 它只打印“b3” 这是到目前为止的代码Javascript 压缩字符串的算法,javascript,algorithm,compression,Javascript,Algorithm,Compression,我想写一个函数来压缩字符串的字符,比如'bbbab'将被转换成'b3ab',我被卡住了 它只打印“b3” 这是到目前为止的代码 let string='bbbab'; 让字母=string.split(“”); 设currentAlphabetLetter=字母[0]; 让计数=0; 让newString=[]; string.split(“”).forEach(字母=>{ 如果(字母===当前字母){ 计数++; }否则{ 如果(计数>0){ push(`currentAlphabetLet
let string='bbbab';
让字母=string.split(“”);
设currentAlphabetLetter=字母[0];
让计数=0;
让newString=[];
string.split(“”).forEach(字母=>{
如果(字母===当前字母){
计数++;
}否则{
如果(计数>0){
push(`currentAlphabetLetter}${count}`);
}否则{
newString.push(`${letter}`);
}
计数=0;
当前字母=字母;
}
})
console.log(新闻字符串)
当您开始一个新字母时,您需要将计数
设置为1
,否则您不计算字符的第一次出现次数
这在字符串的开头不是问题,因为您处理第一个字母两次:使用let current alphabetletter=letters[0]提取它
然后在forEach
的第一次迭代中再次处理它。若要使字符串的开头与其他匹配项相同,应在以第2个字符开始的子字符串上进行迭代
您应该附加到字符串,而不是推到数组上
当count
为1
时,您需要追加currentAlphabetLetter
,而不是letter
let string='bbbab';
让字母=string.split(“”);
设currentAlphabetLetter=字母[0];
让计数=1;
让newString=“”;
string.substr(1).split(“”).forEach(字母=>{
如果(字母===当前字母){
计数++;
}否则{
如果(计数>1){
newString+=`${currentAlphabetLetter}${count}`;
}否则{
newString+=`${currentAlphabetLetter}`;
}
计数=1;
当前字母=字母;
}
});
//处理最后一封信
如果(计数>1){
newString+=`${currentAlphabetLetter}${count}`;
}否则{
newString+=`${currentAlphabetLetter}`;
}
console.log(新闻字符串)这样的代码应该适合你
let string = 'bbbab';
let newString = [];
if (string.length < 2) { console.log(string); }
else {
let letters = string.split("");
let prev = letters[0];
let count = 1;
for( var i = 1; i < letters.length; i++) {
if (letters[i] !== prev) {
count > 1 ? newString.push(`${prev}${count}`) : newString.push(`${prev}`);
count = 1;
} else {
count++;
}
prev = letters[i];
}
/* last element push */
count > 1 ? newString.push(`${prev}${count}`) : newString.push(`${prev}`);
console.log(newString.join(""));
}
let string='bbbab';
让newString=[];
if(string.length<2){console.log(string);}
否则{
让字母=string.split(“”);
设prev=字母[0];
让计数=1;
对于(变量i=1;i1?newString.push(`${prev}${count}`):newString.push(`${prev}`);
计数=1;
}否则{
计数++;
}
prev=字母[i];
}
/*最后一个元素推*/
count>1?newString.push(`${prev}${count}`):newString.push(`${prev}`);
console.log(newString.join(“”);
}
您可以执行以下操作:
var str='bbbabcc',
res=[…str].reduce((r,c,i)=>(r[r.length-1][0]==c|||!i)?(r[r.length-1]+=c,r)
:r.concat(c),[“”]
.reduce((r,s)=>r+s[0]+(s.length-1?s.length:),“”);
控制台日志(res)代码>“我被卡住了”您必须提供更多关于您的问题的信息。你到底是怎么被困住的?你有错误吗?您的代码是否不会产生预期的输出?你得到了哪种输出?你期望什么?输入是什么?请看。你在哪里被卡住了?只是在打印或在数组中添加b3。你能更好地解释一下吗?@totalnoob我希望这能有所帮助。