题目
来源:百度前端学院
js
/*去掉字符串 str 中,连续重复的地方*/function removeRepetition(str) {// do something}// 测试用例console.log(removeRepetition('aaa')) // ->aconsole.log(removeRepetition('abbba')) // ->abaconsole.log(removeRepetition('aabbaabb')) // ->ababconsole.log(removeRepetition('')) // ->console.log(removeRepetition('abc')) // ->abc
解法
js
function removeRepetition(str) {let strArr = [...str]const result = strArr.filter((s, i, arr) => s !== arr[i + 1]).join('')return result}console.log(removeRepetition('aaa')) // ->aconsole.log(removeRepetition('abbba')) // ->abaconsole.log(removeRepetition('aabbaabb')) // ->ababconsole.log(removeRepetition('')) // ->console.log(removeRepetition('abc')) // ->abc
如果没有限定条件说是“连续重复”,就可以用 Set:
js
function removeRepetition(str) {let strArr = [...new Set(str)]return strArr.join('')}console.log(removeRepetition('aaa')) // ->aconsole.log(removeRepetition('abbba')) // ->abconsole.log(removeRepetition('aabbaabb')) // ->abconsole.log(removeRepetition('')) // ->console.log(removeRepetition('abc')) // ->abc