關于lastIndexOf的用法#JS_codewar_3

題目

傳入一個字符串,返回一個新的字符串。如果舊字符串中字符只出現了一次,則返回'(',反之,則返回')'。忽略大小寫。

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,妙妙妙

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,890評論 0 23
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 8,925評論 0 6
  • 晴有風,波浪。關心則亂,人很難在自己在意的事情面前不杞人憂天、胡思亂想!這時候你需要做的,不是想方設法的平復心緒,...
    生虎日記閱讀 198評論 0 0
  • 唧唧復唧唧,想起老逼七。 我們系江浙一帶的人并不多,我班高考總成績第一名英語卻不及格的老七是其中之一。寢室里同是南...
    封狼居胥閱讀 996評論 3 5
  • 第一次看見劉詩詩是在聊齋奇女子,她是單元女主辛十四娘,我媽媽說這個女孩子會紅,我說她不夠漂亮。 后來再次見到她,是...
    陳蝸牛閱讀 957評論 8 11