[leetcode, JS] 2108. Find First Palindromic String in the Array

mxxn·2023년 12월 13일
0

leetcode

목록 보기
146/198

문제

문제 링크 : Find First Palindromic String in the Array

풀이

/**
 * @param {string[]} words
 * @return {string}
 */
var firstPalindrome = function(words) {
    for(let word of words) {
        const reverseWord = word.split('').reverse().join('')
        if(reverseWord === word) return word
    }

    return ''
};
  1. for문을 통해 word와 reverse한 값이 일치한지 비교하여 return
  • Runtime 85 ms, Memory 50.22 MB

다른 풀이

/**
 * @param {string[]} words
 * @return {string}
 */
var firstPalindrome = function(words) {
    for (let i = 0; i < words.length; i++) {
        const word = words[i];
        let isPalindromic = true;
        for (let j = 0; j < word.length/2; j++) {
            if (word[j] !== word[word.length - j - 1]) {
                isPalindromic = false;
                break;
            }
        }
        if (isPalindromic) return word;
    }
    return '';
};
  1. word별로 알파벳 전부를 비교할 필요가 없는 방식
  • Runtime 61 ms, Memory 46.24 MB
profile
내일도 글쓰기

0개의 댓글