删除连续的重复字符

时间:2018-09-12 15:51:16

标签: javascript algorithm

我正在尝试从字符串中删除连续的重复字符。因此,aabbcde的输入应输出为cde

我编写了以下代码,但输出不正确。我不明白为什么。

var a = "aabbccddeef"
var ncopy = a;

let leftPointer = 0;
let rightPointer = 1;

let posList = [];

while (true) {
  if (a[leftPointer] == a[rightPointer]) {
    ncopy = ncopy.replace(a.slice(leftPointer, rightPointer + 1), '')
    leftPointer += 2
    rightPointer = leftPointer + 1;
    if (leftPointer >= a.length || rightPointer >= a.length) {
      break;
    }
  } else {
    leftPointer++;
    rightPointer++;
  }
}

console.log(ncopy);

3 个答案:

答案 0 :(得分:2)

您可以使用简单的正则表达式来做到这一点:

'aabbbcde'.replace(/(.)\1+/g, '')

结果:

'cde'

摘要:

var a = 'aabbbcde';
var result = a.replace(/(.)\1+/g, '');
console.log(result);

答案 1 :(得分:0)

您可以使用以下递归函数:

const input = 'aabbccddeeffg';


function getResult(str) {

  const newStr = str.match(/(.)\1*/g).filter(str => !((str.length % 2 === 0) && (str.split('').every((char,i,arr) => char === arr[0])))).join('');

  return newStr === str ? newStr : getResult(newStr)

}

const result = getResult(input);

console.log(result);

答案 2 :(得分:0)

'aabbccde'
  .split('')
  .reduce(
    (acc, cur) => {
      if (acc.indexOf(cur) !== -1) {
        return acc.slice(acc.length);
      }
      return [...acc, cur];
    }
  )
  .join('')