关于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,959评论 0 23
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,928评论 0 6
  • 晴有风,波浪。关心则乱,人很难在自己在意的事情面前不杞人忧天、胡思乱想!这时候你需要做的,不是想方设法的平复心绪,...
    生虎日记阅读 198评论 0 0
  • 唧唧复唧唧,想起老逼七。 我们系江浙一带的人并不多,我班高考总成绩第一名英语却不及格的老七是其中之一。寝室里同是南...
    封狼居胥阅读 1,001评论 3 5
  • 第一次看见刘诗诗是在聊斋奇女子,她是单元女主辛十四娘,我妈妈说这个女孩子会红,我说她不够漂亮。 后来再次见到她,是...
    陈蜗牛阅读 960评论 8 11