[LeetCode] 647. Palindromic Substrings

2024. 10. 15. 18:04·PS/LeetCode
반응형

문제

https://leetcode.com/problems/palindromic-substrings/description/

 

입력

s: String = 문자열 

1 <= s.count <= 1000

결과

ans: Int = s의 부분 문자열에서 찾을 수 있는 모든 회문 개수

해석

회문이란 중심을 기준으로 대칭되는 문자열이다. 

 

크게 두가지 종류가 있다. 

 

  1. 홀수 문자열 회문
    • abcba 
    • 중심을 기준으로 정확히 대칭
    • 왼쪽 포인터와 오른쪽 포인터가 c를 기준으로 출발하면 됨 
  2. 짝수 문자열 회문
    • abccba
    • 중심이 딱 보이지는 않음
    • 왼쪽 포인터는 2번 index , 오른쪽 포인터는 3번인덱스를 기준으로 출발하면 됨
    • 즉 중심이 2개 

그렇기 때문에 중심을 하나씩 움직이며 각 기준의 홀수 회문과 짝수 회문을 모두 더해가면 s의 부부 문자열의
모든 회문을 찾을 수 있다. 

 

코드

import Foundation 

class Solution {

    func countSubstrings(_ s: String) -> Int {
        let s = Array(s)
        let n = s.count
        
        func countPalindromes(left l : Int, right r: Int) -> Int {
            var count: Int = 0
            var l = l
            var r = r
            
            while 0 <= l && r < n && s[l] == s[r] {
                count += 1 
                l -= 1 
                r += 1 
            } 

            return count 
        }

    var answer: Int = 0

    for center in 0..<n {

        // 첫 left 와 right가 같다는건 홀수길이의 회문 검사  aba 같은 경우 
        answer += countPalindromes(left: center, right: center)

        // 다르게 시작하면 짝수길이의 회문 검사 abab 같은 경우 
        answer += countPalindromes(left: center, right: center+1)

    }

    return answer    

    }
}

 

반응형

'PS > LeetCode' 카테고리의 다른 글

Product of Array Except Self  (0) 2025.01.05
Best Time to Buy and Sell Stock  (0) 2025.01.05
Two Sum  (0) 2025.01.05
[LeetCode] 3. Longest Substring Without Repeating Characters  (0) 2024.10.24
[LeetCode] 459. Repeated Substring Pattern  (0) 2024.10.15
'PS/LeetCode' 카테고리의 다른 글
  • Best Time to Buy and Sell Stock
  • Two Sum
  • [LeetCode] 3. Longest Substring Without Repeating Characters
  • [LeetCode] 459. Repeated Substring Pattern
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (329) N
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (41)
        • swift (34)
        • python (6)
        • Kotlin (1)
      • iOS (134)
        • UIKit (37)
        • Combine (1)
        • SwiftUI (34)
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (21)
        • 어노테이션 (6)
        • 튜토리얼 (14)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
      • AI (11) N
        • 이론 (10) N
        • MCP (1)
        • LangGraph (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Tuist
    dp
    SwiftUI
    boostcamp
    GIT
    Swift
    AVFoundation
    property
    Spring
    dispatch
    프로그래머스
    UIKit
    protocol
    dfs
    IOS
    lifecycle
    백준
    투포인터
    CS
    concurrency
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
[LeetCode] 647. Palindromic Substrings
상단으로

티스토리툴바