[LeetCode] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence

Chobby·2025년 8월 25일
1

LeetCode

목록 보기
527/582

😎풀이

  1. sentence를 한 칸의 공백을 기준으로 분리
  2. 분리된 배열을 순회
    2-1. 각 문자가 searchWord를 접두사로 시작되는지 확인
    2-2. 접두사가 맞다면 현재의 인덱스(1-인덱싱 기준) 반환
  3. 접두사를 갖는 단어가 없다면, -1 반환환
function isPrefixOfWord(sentence: string, searchWord: string): number {
    const splitted = sentence.split(' ')
    for(let i = 0; i < splitted.length; i++) {
        const str = splitted[i]
        if(str.startsWith(searchWord)) return i + 1
    }
    return -1
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글