题目
传入一个字符串,返回一个新的字符串。如果旧字符串中字符只出现了一次,则返回'(',反之,则返回')'。忽略大小写。
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){
const newWord = word.toLowerCase();
let box = [];
for(i=0; i<newWord.length; i++){
let idx = newWord.indexOf(newWord[i]);
if (newWord.indexOf(newWord[i], idx + 1) > 0) { //whether duplicated with lateral
box.push(')');
} else if(newWord.indexOf(newWord[i]) < i) { //whether duplicated with before
box.push(')');
} else {
box.push('(');
}
}
return box.join('');
}
别人的
function duplicateEncode(word){
return word
.toLowerCase()
.split('')
.map( function (a, i, w) {
return w.indexOf(a) == w.lastIndexOf(a) ? '(' : ')'
})
.join('');
}
感想
想到了indexOf,却没有想到lastIndexOf,妙妙妙