最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reducing duplicate characters in a string to a given minimum - Stack Overflow

programmeradmin1浏览0评论

I was messing around with the first question here: Reduce duplicate characters to a desired minimum and am looking for more elegant answers than what I came up with. It passes the test but curious to see other solutions. The sample tests are:

reduceString('aaaabbbb', 2) 'aabb'  
reduceString('xaaabbbb', 2) 'xaabb' 
reduceString('aaaabbbb', 1) 'ab'    
reduceString('aaxxxaabbbb', 2)  'aaxxaabb'

and my solution (that passes these tests):

reduceString = function(str, amount) {
  var count = 0;
  var result = '';
  for (var i = 0; i < str.length; i++) {
    if (str[i] === str[i+1]) {
      count++;
      if (count < amount) {
        result += str[i];
      }
    } else {
      count = 0;
      result += str[i];
    } 
  };
  return result;
}

I was messing around with the first question here: Reduce duplicate characters to a desired minimum and am looking for more elegant answers than what I came up with. It passes the test but curious to see other solutions. The sample tests are:

reduceString('aaaabbbb', 2) 'aabb'  
reduceString('xaaabbbb', 2) 'xaabb' 
reduceString('aaaabbbb', 1) 'ab'    
reduceString('aaxxxaabbbb', 2)  'aaxxaabb'

and my solution (that passes these tests):

reduceString = function(str, amount) {
  var count = 0;
  var result = '';
  for (var i = 0; i < str.length; i++) {
    if (str[i] === str[i+1]) {
      count++;
      if (count < amount) {
        result += str[i];
      }
    } else {
      count = 0;
      result += str[i];
    } 
  };
  return result;
}
Share asked Jun 7, 2016 at 0:29 Rk220Rk220 1812 silver badges10 bronze badges 2
  • Presumably you want sequential repeated characters, not just repeated? – RobG Commented Jun 7, 2016 at 2:20
  • @RobG yup based off the samples it looks like that's what they were testing for. – Rk220 Commented Jun 7, 2016 at 18:27
Add a ment  | 

6 Answers 6

Reset to default 6

Just use regular expressions.

var reduceString = function (str, amount) {
    var re = new RegExp("(.)(?=\\1{" + amount + "})","g");
    return str.replace(re, "");
}

I guess my best solution would be like

var str = "axxxaabbbbcaaxxxaab",
 redStr = (s,n) => s.replace(/(\w)\1+/g,"$1".repeat(n));
console.log(redStr(str,2));

I tried to make it as short as possible:

reduceString = function(str, amount) {
    var finalString = '', cL = '', counter;
    str.split('').forEach(function(i){
        if (i !== cL) counter = 0;
        counter++;
        cL = i;
        if (counter <= amount ) finalString = finalString + i;
    });
    return finalString;
}

You can use reg expression instead. tested in javascript.

how it works:

(.) //match any character
\1 //if it follow by the same character
+{2 //more than 1 times
/g //global
$1 //is 1 time by $1$1 is 2 times 

     reduceString('aaaabbbb', 2) 
     reduceString('xaaabbbb', 2) 
            reduceString('aaaabbbb', 1)     
            reduceString('aaxxxaabbbb', 2) 

            function reduceString(txt,num)
            {
                var canRepeat=['$1'];
               for (i=1;i<num;i++)
               {
                  canRepeat.push('$1')
               }
                canRepeat = canRepeat.join('');

                console.log(txt.replace(/(.)\1{2,}/g, canRepeat))

            }      

With regex:

var reduceString = function(str, amount) {
var x = [ ...new Set(str) ];
for (var c of x){
    var rex = new RegExp(c + '{'+amount+',}','g');
    str = str.replace(rex,string(c,amount));
  }
  return str;
};

var string = function(c,amount){
    for(var i=0,s="";i<amount;i++)s+=c;
    return s;
};

Up above regex solutions are much more better, but here is my accepted solution with reduce:

  1. make an array from string via spread operator
  2. Check the previous item
  3. find how many times char is repeated in result string
  4. otherwise concat result string with the current char

Don`t forget to use the second argument as the initial value, and return for each cases

reduceString = function(str, amount) {
    return [...str].reduce(((res, cur)=>{
        if(res.length && cur === res[res.length-1]){
            dupsCount = [...res].filter(char => char === cur).length
            if(dupsCount===amount){
                return res;
            }
            else {
                res+=cur;
                return res;
            }
        }
        res+=cur;
        return res;
    }),"")
}
发布评论

评论列表(0)

  1. 暂无评论