๐Ÿฅž BE
home

5_Longest Palindromic Substring

๋‹ด๋‹น์ž
์™„๋ฃŒ ์—ฌ๋ถ€
Solved
์š”์•ฝ
๋‚ ์งœ
2024/06/27
ํƒœ๊ทธ
๊ตฌํ˜„
๋ฌธ์ž์—ด
๋‚œ์ด๋„
Medium
์ถœ์ฒ˜
LeetCode

์ฝ”๋“œ

class Solution { public String longestPalindrome(String s) { // ์ธ๋ฑ์‹ฑ์„ ์œ„ํ•œ ๋ณ€์ˆ˜ int left = 0, right = 0; for (int i = 0; i < s.length(); i++) { // ํ™€์ˆ˜ ๊ธธ์ด ํŒฐ๋ฆฐ๋“œ๋กฌ int len1 = expandCenter(s, i, i); // ์ง์ˆ˜ ๊ธธ์ด ํŒฐ๋ฆฐ๋“œ๋กฌ int len2 = expandCenter(s, i, i +1); // ๋‘˜ ์ค‘ ์ตœ๋Œ€ ๊ธธ์ด ์„ ํƒ int len = Math.max(len1, len2); // ๊ธธ์ด๊ฐ€ ๋” ๊ธธ ๊ฒฝ์šฐ ์ธ๋ฑ์Šค ์—…๋ฐ์ดํŠธ if (len > right - left) { left = i - (len -1) / 2; right = i + len / 2; } } // ๊ฐ€์žฅ ๊ธด ํŒฐ๋ฆฐ๋“œ๋กฌ ๋ฆฌํ„ด return s.substring(left, right +1); } private int expandCenter(String s, int left, int right) { // left์™€ right ์ธ๋ฑ์Šค๊ฐ€ ๋ชจ๋‘ ๋ฒ”์œ„ ๋‚ด์— ์žˆ์–ด์•ผ ํ•˜๋ฉฐ, ํŒฐ๋ฆฐ๋“œ๋กฌ์ด์–ด์•ผ ํ•จ. while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) { // ์กฐ๊ฑด ๋งŒ์กฑ ์‹œ ๋ฒ”์œ„ ํ™•์žฅ left--; right++; } // ํ™•์žฅ ํ›„ ๊ธธ์ด ๋ฐ˜ํ™˜ return right - left -1; } }
Java
๋ณต์‚ฌ

๋‹ค๋ฅธ ํ’€์ด (from ์ƒ๊ตฌ๋‹˜ ์ฝ”๋“œ)

public class Ch06_06 { public String longestPalindrome(String s) { if (s.length() < 2) return s; for (int windowSize = s.length(); windowSize > 1; windowSize--) { for (int i = 0; i <= s.length() - windowSize; i++) { if (isPalindrome(s, i, i + windowSize - 1)) { return s.substring(i, i + windowSize); } } } return s.substring(0, 1); } private boolean isPalindrome(String s, int start, int end) { while (start < end) { if (s.charAt(start) != s.charAt(end)) return false; start++; end--; } return true; } }
Java
๋ณต์‚ฌ
์ด๋ ‡๊ฒŒ ์™„์ „ ํƒ์ƒ‰์œผ๋กœ ์ง๊ด€์ ์œผ๋กœ ์งค์ˆ˜๋„ ์žˆ์ง€๋งŒ ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ ์ข‹์ง€ ์•Š๋‹ค.

๋ฌธ์ œ ํ•ด๊ฒฐ ์•„์ด๋””์–ด

์ค‘์•™ํ™•์žฅ๋ฐฉ์‹์„ ํ™œ์šฉํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ฒ”์œ„ ๋‚ด์—์„œ ํŒฐ๋ฆฐ๋“œ๋กฌ์„ ๋งŒ๋‚ฌ์„ ๋•Œ, ํ•ด๋‹น ๋ถ€๋ถ„๋ถ€ํ„ฐ ํ™•์žฅ๋˜๋Š” ํฌ์ธํ„ฐ๋ฅผ ๊ตฌํ˜„ํ•˜๋Š” ๋กœ์ง์ด ํ•ต์‹ฌ์ด๋‹ค. ๋ฌธ๋ฒ• ์ž์ฒด๋Š” ์–ด๋ ต์ง€ ์•Š์ง€๋งŒ ๋ฌธ์ œ ์ดํ•ด ๋‚œ์ด๋„๊ฐ€ ๋†’์•˜๋‹ค.