题目
the goal of this exercise is to convert a string to a new string where each character in the new string is "(", if the character appears only once in the original string, so ')' if that character appears more than once in the origin string
例子
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
题解
本来我是想,循环字符串,然后如果出现超过2次,则显示为")", 否则为"(",但是我觉得他主要考察你对数组集合的运用情况,下面就是最佳的答案(如果你有更好的写法,欢迎来评论)
function duplicateEncode(word) {
return word
.toLowerCase()
.split('')
.reduce((acc, char, i, arr) => {
const symbol = arr.filter(item => item === char).length < 2 ? '(' : ')'
return acc + symbol
}, '')
}
总结
数组的集合方法,forEach,filter,map,reduce 在日常的编程中非常重要,一定要使用!这样代码才能更具有阅读性