删除连续的重复字符 [英] Removing consecutive duplicate characters

查看:114
本文介绍了删除连续的重复字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to remove consecutive duplicate characters from the string. So the input of aabbcde should output as cde.

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

I wrote the following code, but I am getting the incorrect output. I could not understand why.

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

推荐答案

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

You can do it with a following recursive function:

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

这篇关于删除连续的重复字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆