Duplicate Encoder 重复编码器
2019-03-03 本文已影响0人
小7丁
The goal of this exercise is to convert a string to a new string where each character in the new string is '(' if that character appears only once in the original string, or ')' if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples:
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
题目的大概意思就是讲一段字符串中没有重复的字母就转换成
"("
,重复了的字母就转换成")"
首先看到字符串的题,就要想到大小写并且将其转换成数组。
function duplicateEncode(word){
let arr = word.toUpperCase().split('')
}
要找到对应重复的字母,就联想到对象
key
值多的就➕1
所以创建一个 map
的哈希表存重复的次数
let map = {}
arr.forEach(i => {
if (map[i]) {
map[i] += 1
} else {
map[i] = 1
}
})
console.log(map) // { R: 1, E: 3, C: 1, D: 1 }
对数组再一次遍历,将重复的字母转成对应的括号
arr.forEach((i, key) => {
if (map[i] === 1) {
arr[key] = '('
} else {
arr[key] = ')'
}
})
return arr.join('')
更好的方法是如下
function duplicateEncode(word) {
return word.toLowerCase().replace(/./g, m => word.indexOf(m) == word.lastIndexOf(m) ? '(' : ')');
}