First non-repeating character

SungJunEun·2021년 11월 9일
0

Codewars 문제풀이

목록 보기
12/26
post-thumbnail

Description:

Write a function named first_non_repeating_letter that takes a string input, and returns the first character that is not repeated anywhere in the string.

For example, if given the input 'stress', the function should return 't', since the letter t only occurs once in the string, and occurs first in the string.

As an added challenge, upper- and lowercase letters are considered the same character, but the function should return the correct case for the initial letter. For example, the input 'sTreSS' should return 'T'.

If a string contains all repeating characters, it should return an empty string ("") or None -- see sample tests.

My solution:

function firstNonRepeatingLetter(s) {
  let box = {};
  let index;
// make object of key of string and value of the countfor(let element of s) {
    element = element.toUpperCase();
    if(!box[element]) {
      box[element] = 1;
    } else {
      box[element] ++;
    }
  }
// get index which has one existencefor(item of Object.keys(box)) {
    if(box[item] == 1) {
      index = item;
      console.log(index);
      break;
    }
  }
// handle empty & all repeating caseif(!index) {
    return '';
  }
// normal casesfor(let element of s) {
    if(element.toUpperCase() == index.toUpperCase() ) {
      return element;
    }
  }
}

Best solutions:

function firstNonRepeatingLetter(s) {
  for(let i of s) {
    if(s.match(new RegExp(i,"gi")).length === 1) {
      return i;
    }
  }
  return '';
}
  • string.match(regexp)

    문자열이 주어진 정규식이랑 일치되는 부분을 반환한다.

  • 정규표현식 gi

    전부, 대문자&소문자 상관없이 찾아라

profile
블록체인 개발자(진)

0개의 댓글