[leetcode, JS] 1876. Substrings of Size Three with Distinct Characters

mxxn·2023년 11월 21일
0

leetcode

목록 보기
127/198

문제

문제 링크 : Substrings of Size Three with Distinct Characters

풀이

/**
 * @param {string} s
 * @return {number}
 */
var countGoodSubstrings = function(s) {
    let cnt = 0;
    for(let i=0; i<s.length-2; i++) {
        let str = s.slice(i, i+3)
        if( [...new Set(str.split(''))].join('') === str ) cnt++
    }

    return cnt
};
  1. for문을 통해 길이 3의 연속된 문자열을 만들
  2. 해당 문자열이 중복된 값이 없는지 체크하여 cnt++하여 cnt값 return
  • Runtime 53 ms, Memory 44.32MB

다른 풀이

/**
 * @param {string} s
 * @return {number}
 */
var countGoodSubstrings = function(s) {
    let cnt = 0;
    for(let i=0; i<s.length-2; i++) {
        if(new Set(s.slice(i, i+3).split('')).size === 3 ) cnt++
    }

    return cnt
};
  1. 첫번째 풀이와 같은 방식이지만 set을 join하여 str과 비교하는 것이 아니라, set의 size가 3인 경우로 체크
  • Runtime 55 ms, Memory 43.23MB
profile
내일도 글쓰기

0개의 댓글