넘치게 채우기

[LeetCode] 2108. Find First Palindromic String in the Array 본문

PS/LeetCode

[LeetCode] 2108. Find First Palindromic String in the Array

riveroverflow 2024. 2. 13. 10:53
728x90
반응형

https://leetcode.com/problems/find-first-palindromic-string-in-the-array/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Leetcode - Find First Palindromic String in the Array

문제 유형 : 문자열 처리

문제 난이도 : Easy

 

문제

Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".

A string is palindromic if it reads the same forward and backward.

문자열 배열 words가 주어진다.

첫 팰린드롬 문자를 반환하시오. 없으면 빈 문자열을 반환하시오.

 

풀이

모든 문자열들을 순차적으로 순회하면서, 팰린드롬인지 아닌지 체크하면 된다. 팰린드롬이라면 그 문자열을 반환한다.

모든 문자열들을 순회한 뒤 팰린드롬이 없으면 빈 문자열을 반환한다.

팰린드롬인지 아닌지에 대한 체크는 양 끝 인덱스부터 시작해서 중앙까지의 문자들을 비교해보면 된다.

 

코드

C++

class Solution {
public:
    bool isP(string& word) {
        for(int i = 0; i < word.size()/2; i++) {
            if(word[i] != word[word.size()-i-1]) return false;
        }
        return true;
    }

    string firstPalindrome(vector<string>& words) {
        for(string &word: words) {
            if(isP(word)) return word;
        }

        return "";
    }
};

Go

func isP(word string) bool {
    for i := 0; i < len(word)/2; i++ {
        if word[i] != word[len(word)-i-1] {return false}
    }
    return true
}

func firstPalindrome(words []string) string {
    for _, word := range words {
        if isP(word) {return word}
    }
    return ""
}
728x90
반응형