지난 공부기록/알고리즘 풀이

Python - Algorithm #6

hkl22 2024. 6. 18. 10:10

Python Algorithm

LeetCode

2108. Find First Palindromic String in the Array

  • 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.
  • Constraints:
    • ≤ words.length  100
    •  words[i].length  100
    • words1[i] consists only of lowercase English letters.
class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        answer = ""
        for word in words:
            # 만약 word가 palindrome이라면 answer에 word를 지정하고 break!
            # word[::-1]
            if word == word[::-1]:
                answer = word
                break
        return answer
class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        for i in words:
            if i == i[::-1]:
                return i
        return ""

1550. Three Consecutive Odds

  • Given an integer array arr, return true if there are three consecutive odd numbers in the array. Otherwise, return false.
  • Constraints:
    • 1 ≤ arr.length ≤ 1000
    • 1 ≤ arr[i] ≤ 1000
class Solution:
    def threeConsecutiveOdds(self, arr: List[int]) -> bool:
        answer = False
        for i in range(len(arr)-2):
            if arr[i] % 2 == 1 and arr[i + 1] % 2 == 1 and arr[i + 2] % 2 == 1:
                answer = True
                break
        return answer

class Solution:
    def threeConsecutiveOdds(self, arr: List[int]) -> bool:
        answer = False
        cnt = 0
        for num in arr:
            # 만약 현재 숫자가 짝수라면 여기서부터는 연속된 홀수가 0
            # 만약 현재 숫자가 홀수라면 직전 홀수 개수 + 1만큼 연속된 홀수가 있는 것
            # 만약 연속된 홀수가 3개 이상 등장한다면 answer를 True로 놓고 break
            if num in arr:
                if num % 2 == 0:
                    cnt = 0
                else:
                    cnt += 1
            if cnt >= 3:
                answer = True
                break
        return answer
class Solution:
    def threeConsecutiveOdds(self, arr: List[int]) -> bool:
        for i in range(len(arr)-2):
            cnt = 0
            for j in range(3):
                if arr[i + j] % 2 != 0:
                    cnt += 1
            if cnt == 3:
                return True
        return False

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

https://leetcode.com/problems/three-consecutive-odds/

'지난 공부기록 > 알고리즘 풀이' 카테고리의 다른 글

SQL - Algorithm #8  (0) 2024.06.20
SQL - Algorithm #7  (0) 2024.06.19
Python - Algorithm #5  (0) 2024.06.17
Python - Algorithm #4  (0) 2024.06.12
Python - Algorithm #3  (0) 2024.06.11