Fe-interview: [js] 第302天 写一个方法删除字符串中所有相邻重复的项

Created on 11 Feb 2020  ·  4Comments  ·  Source: haizlin/fe-interview

第302天 写一个方法删除字符串中所有相邻重复的项

我也要出题

js

Most helpful comment

可以利用正则:

'aabbaaaaccdeee'.replace(/(.)\1*/g, '$1');  // abacde

All 4 comments

function delneighbor(string) {
    if(string.length <= 1) {
        return string
    }
    let prev = string[0];
    let result = prev;
    let i = 1;
    while(i < string.length) {
        const current = string[i++];
        if(current == prev) {
            continue;
        }
        prev = current;
        result += current;
    }
    return result;
}

可以利用正则:

'aabbaaaaccdeee'.replace(/(.)\1*/g, '$1');  // abacde

let s='2211dddfccc';
let arr = Array.from(new Set([...s])).join(''); //21dfc

 function delneighbor(str) {
      if (str.length <= 1) {
        return str;
      }
      // 先转成数组
      let arr = str.split("");
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] == arr[i + 1]) {
          arr.splice(i, 1)
        }
      }
      // join不改变原数组
      let newStr = arr.join("");
      return newStr
    }
    console.log(delneighbor('helssaabssaavvccblo'))
Was this page helpful?
0 / 5 - 0 ratings