Daily question: Remove the characters with the fewest occurrences from the string without changing the order of the original characters.

Daily question

Remove the characters that appear the least frequently in the string without changing the order of the original characters. Realize deleting the character with the least occurrence in the string. If there are multiple characters with the least occurrence, delete all the characters with the least occurrence. Output the string after deleting these words, and keep the other characters in the string in their original order.

Ideas

  • Count the number of characters through forEaech
  • Find the minimum number of characters
  • Array the minimum number of characters
  • Regular global replacement of the characters with the fewest occurrences

let c = 'accacddaddbb';
let arr = c.split('');
let crrute = {
    
    };
/*通过forEaech来统计字符个数*/
arr.forEach((item)=>{
    
    
  if(!crrute[item]){
    
    
    crrute[item] = 1;
  }else{
    
    
    crrute[item] += 1;
  }
})
/*通过reduce来统计字符个数*/
// crrute = arr.reduce((acc,curr) => {
    
    
//  acc[curr] ? acc[curr] += 1 : acc[curr] = 1
//  return acc
// },{})
//console.log(crrute);

/*找出最少的字符的个数*/
let valus = Object.values(crrute)
let result = valus.reduce((acc, curr)=>{
    
    
  return Math.min(acc,curr);
},Infinity);

/*将最少的字符组成数组*/
let keyArr = [];
for (key in crrute){
    
    
    if(result == crrute[key]){
    
    
      keyArr.push(key)
    }
}
/*正则全局替换掉出现最少得字符*/
let n = '';
keyArr.forEach((item)=>{
    
    
  n = c.replace(new RegExp(item, 'g'),'') 
  c = n;
})

console.log(c);

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/134927571