[LeetCode] 2047. Number of Valid Words in a Sentence

Chobby·6일 전
1

LeetCode

목록 보기
657/710

😎풀이

  1. 특정 문자가 옳은지 판단하는 헬퍼 함수 정의
    1-1. 숫자가 포함되지 않아야 함
    1-2. 하이픈(-)은 문자 사이에 위치해야함
    1-3. 하이픈(-)은 최대 한 개만 존재 가능
    1-4. 특수 문자는 단어 사이에 위치해야함
    1-5. 특수 문자로 단어가 시작해선 안됨
    1-6. 특수 문자는 두 개 이상 연속해서 등장할 수 없음
  2. sentence 순회
    2-1. sentence를 한 개 이상의 공백으로 분리하여 단어 목록을 생성
  3. 헬퍼 함수를 통해 각 단어가 유효한지 검증
    3-1. 유효 하다면 카운트 증가
  4. 카운트 된 옳은 단어의 수 반환
function countValidWords(sentence: string): number {
    const words = []
    let curWord = ''
    for(const char of sentence) {
        if(char === ' ') {
            if(!curWord) continue
            words.push(curWord)
            curWord = ''
            continue
        }
        curWord += char
    }
    if(curWord) words.push(curWord)
    let validWords = 0
    for(const word of words) {
        if(isValidWord(word)) validWords++
    }
    return validWords
};

function isValidWord(word: string) {
    const hasDigit = word.match(/[0-9]+/g)
    if(hasDigit) return false
    if(word[0] === '-' || word.at(-1) === '-') return false
    const mostOneHypen = word.match(/[\-]+/g)
    if(mostOneHypen && mostOneHypen.length > 1) return false
    const amongAlphabet = word.match(/[a-z][^\w\s\-][a-z]/g)
    if(amongAlphabet) return false
    const startWithPunctuation = word.match(/^[^\w\s][a-z]+/g)
    if(startWithPunctuation) return false
    const doublePunctuation = word.match(/[^\w\s]{2,}/g)
    if(doublePunctuation) return false
    return true
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글