6.Duplicate Encoder

103 阅读1分钟

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) {
    var obj = {};
    var wordArr = word.toLowerCase().split('');
    var newWord = '';
    wordArr.forEach((cur) => {
      if (obj[cur]) {
        obj[cur]++;
      } else {
        obj[cur] = 1;
      }
    });
    
    wordArr.forEach((item) => {
      newWord += obj[item] <= 1 ? '(' : ')';
    })
    
    return newWord
}
unlock solution
参考一:
function duplicateEncode(word) {
    var unique = ''
    word = word.toLowerCase()
    for (var i = 0; i < word.length; i++) {
        if (word.lastIndexOf(word[i]) == word.indexOf(word[i])) {
            unique += '('
        } else {
            unique += ')'
        }
    }
    return unique
}


参考二:
function duplicateEncode(word) {
    return word.toLowerCase().split('').map((a, i ,w) => {
        return w.indexOf(a) == w.lastIndexOf(a) ? '(' : ')'
    })
}


剖析思路:若lastIndexOf和indexOf返回的下标相同,说明没有重复的值

▪ Array.prototype.lastIndexOf(searchEle, fromIndex)
searchEle: 被查找的元素
fromIndex: 从次位置开始逆向查找。默认为数组长度减1,即整个数组被查找
返回值: 数组中该元素最后一次出现的索引,如未找到返回-1