728x90
반응형
문제 url: https://leetcode.com/problems/longest-palindromic-substring/
문제 해석
s라는 문자열을 입력받을 때, 해당 문자열 내에서 앞뒤로 봐도 똑같은 글자들 중 가장 긴 글자를 찾아내면 된다.
풀이 방법
풀이 접근 과정
기존에 프로그래머스 Level3 문제에서 가장 긴 팰린드롬 문제를 풀었던 적이 있다.
그 풀이와 유사하게 풀었다.
최종 소스코드
class Solution {
fun longestPalindrome(s: String): String {
var cnt = 0
var answerIdx = Pair(0,0)
fun palindrom(startIndex: Int, endIndex: Int) {
val size = endIndex - startIndex + 1
val midIndex: Int = size / 2
var isCorrect = true
for (index in 0 until midIndex) {
if (s[index+startIndex] != s[endIndex-index]) {
isCorrect = false
break
}
}
if (isCorrect) {
cnt = size
answerIdx = Pair(startIndex, endIndex)
}
if (startIndex <= endIndex-1 && size-1 > cnt) palindrom(startIndex, endIndex-1)
}
for (i in 0 .. s.length-2) {
if (i <= s.length-1 && s.length-1 - i + 1 > cnt) palindrom(i, s.length-1)
}
return s.substring(answerIdx.first, answerIdx.second+1)
}
}
문자를 모두 하나하나 비교하는 방법을 사용하였다.
시작 인덱스부터 특정 길이까지 문자열을 자르고, 갈린 문자열 길이의 가운데 인덱스를 기준으로 대칭되는 문자를 비교한다.
대칭되는 문자 모두가 일치하면 answer에 해당 값의 인덱스를 저장한다.
마지막으로 완성된 인덱스를 기준으로 substring하여 리턴시킨다.
비슷한 문제: https://school.programmers.co.kr/learn/courses/30/lessons/12904
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
728x90
반응형
'LeetCode > Kotlin | Medium' 카테고리의 다른 글
[LeetCode/Kotlin]Medium - 34. Find First and Last Position of Element in Sorted Array (0) | 2024.05.09 |
---|---|
[LeetCode]Medium - 238. Product of Array Except Self (0) | 2024.03.21 |
[LeetCode/Kotlin]442. Find All Duplicates in an Array (1) | 2024.02.14 |
[LeetCode/Kotlin]Medium - 6. Zigzag Conversation (0) | 2023.11.02 |
[LeetCode/Kotlin]Medium - 12. Integer to Roman (0) | 2023.11.02 |