[leetcode, JS] 3120. Count the Number of Special Characters I

mxxn·2024년 7월 28일
0

leetcode

목록 보기
194/198

문제

문제 링크 : Count the Number of Special Characters I

풀이

/**
 * @param {string} word
 * @return {number}
 */
var numberOfSpecialChars = function(word) {
    let obj = {}
    let newWord = word.toLowerCase()
    for(let i=0; i<word.length; i++) { 
        if(!obj[newWord[i]]) {
            if(newWord[i] !== word[i]) {
                if(word.includes(newWord[i])) obj[newWord[i]] = true
            }else {
                if(word.includes(newWord[i].toUpperCase())) obj[newWord[i]] = true
            }
        }
    }

    return Object.values(obj).length
};
  1. 대소문자가 모두 있는 경우의 알파벳을 체크할 obj를 만들고
  2. word를 모두 소문자로 바꾼 newWord도 만들고
  3. obj에 해당 알파벳이 없는 경우만 로직을 타게 하고
  4. word의 i번째와 newWord의 i번째가 다르면( == word의 i번째는 대문자) word에 newWord의 i번째 알파벳이 존재하는지 확인하고
  5. word의 i번째와 newWord의 i번째가 같으면( == word의 i번째는 소문자) word에 newWord의 i번째 알파벳 대문자가 존재하는지 확인
  6. 만들어진 obj를 배열로 바꿔 length를 return
  • Runtime 57 ms, Memory 51.85 MB
profile
내일도 글쓰기

0개의 댓글