[leetcode, JS] 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence

mxxn·2023년 10월 19일
0

leetcode

목록 보기
99/198

문제

문제 링크 : Check If a Word Occurs As a Prefix of Any Word in a Sentence

풀이

/**
 * @param {string} sentence
 * @param {string} searchWord
 * @return {number}
 */
var isPrefixOfWord = function(sentence, searchWord) {
    let arr = sentence.split(' ')
    for(let i=0; i<arr.length; i++) {
        if(arr[i].indexOf(searchWord) === 0) return i+1
    }

    return -1
};
  1. 문자열 sentence를 array로 바꾸고 각 element들이 searchWord로 시작하는지 확인하여 값 return
  • Runtime 49 ms, Memory 41.7 MB

다른 풀이

/**
 * @param {string} sentence
 * @param {string} searchWord
 * @return {number}
 */
var isPrefixOfWord = function(sentence, searchWord) {
    const words = sentence.split(' ');
    for(let i=0;i<words.length;i++){
       if(words[i].startsWith(searchWord))
       return i+1
    }
    return -1
};
  1. startsWith를 사용한 풀이방식
  • Runtime 42 ms, Memory 41.7 MB
profile
내일도 글쓰기

0개의 댓글