将字符串中的重复字符减少到给定的最小值

时间:2016-06-07 00:29:55

标签: javascript string duplicates character

我正在弄乱第一个问题:Reduce duplicate characters to a desired minimum我正在寻找比我想出的更优雅的答案。它通过了测试,但很想知道其他解决方案。样本测试是:

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

和我的解决方案(通过这些测试):

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;
}

5 个答案:

答案 0 :(得分:5)

只需使用正则表达式。

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

答案 1 :(得分:1)

我想我的最佳解决方案就像

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

答案 2 :(得分:0)

我试图让它尽可能短:

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;
}

答案 3 :(得分:0)

您可以使用reg表达式。在javascript中测试。

它如何运作:

(.) //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))

            }      

答案 4 :(得分:0)

使用正则表达式:

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;
};