删除字符串中相邻的重复字母

发布时间 2023-06-06 23:10:41作者: NewBee_2023

题目:去除字符串中相邻且相等的两个字母,得到一个新字符串,并重复进行该操作,知道不能删除为止。
思路:这道题首先想到的是利用循环,定义一个空的结果数组,遍历字符串的每一个元素,与结果数组中的最后一个元素比较,如果不相同,则追加该元素,反之删除数组最后一个元素。实现如下:

const filterDup = string => {
  const result = []
  for(i = 0; i < string.length; i++){
    if(result.length === 0) {
      result.push(string[i])
      continue
    }
    const t = result[result.length - 1]
    if(t !== string[i]){
      result.push(string[i])
    } else {
      result.pop()
    }
  }
  return result.join('')
}

console.log('?->',filterDup("studyzoozcode")); // ?-> studycode