๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/LeetCode

[LeetCode]005. Longest Palindromic Substring JAVA

by Bhinney 2022. 12. 19.
 

Longest Palindromic Substring - LeetCode

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


๐Ÿ“Œ ๋ฌธ์ œ

Given a string s, return the longest palindromic substring in s.

 


๐Ÿ“Œ ๋ฐฉ๋ฒ•

  • ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋งŒํผ ๋ฐ˜๋ณต
  • ๊ทธ ์•ˆ์—์„œ ๋ฐ˜๋ณต๋˜๋Š” ๋ฌธ์ž์—ด ์ค‘ ๊ฐ€์žฅ ๊ธด ๋ฌธ์ž์—ด์„ ์ถœ๋ ฅ
  • ํŒฐ๋ฆฐ๋“œ๋กฌ์€ ๊ฑฐ๊พธ๋กœ ์ฝ์–ด๋„ ์ œ๋Œ€๋กœ ์ฝ๋Š” ๊ฒƒ๊ณผ ๊ฐ™์€ ๋‚ฑ๋ง, ์ˆซ์ž, ๋ฌธ์ž์—ด
  • ๋”ฐ๋ผ์„œ ๋ฐ˜์œผ๋กœ ์ ‘์—ˆ์„ ๋•Œ์—, ์–‘ ์˜†์ด ๊ฐ™์Œ.
  • ๋•Œ๋ฌธ์— ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด i๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์–‘ ์˜†์„ ํ™•์ธ.
class Solution {
    public String longestPalindrome(String s) {
        
        /* ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•  ๊ฒฐ๊ณผ ๊ฐ’ ์„ ์–ธ */
        String result = "";
        
        for (int i = 0; i < s.length(); i++) {
            int len = Math.max(findPalindrome(s,i,i), findPalindrome(s,i,i+1));
            if (result.length() < len) {
                result = s.substring(i - (len-1)/2, i + len/2 + 1);
            }
        }
        return result;
    }
    
    private static int findPalindrome(String s, int start, int end) {
        if (start < 0 || end >= s.length()) {
            return 0;
        }
        
        while(start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
            start--;
            end++;
        }
        
        return end - start - 1;
    }
}

 

'์•Œ๊ณ ๋ฆฌ์ฆ˜ > LeetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[LeetCode]006. Zigzag Conversion JAVA  (0) 2022.12.21
[LeetCode]007. Reverse Integer JAVA  (0) 2022.12.19
[LeetCode] 003. Longest Substring Without Repeating Characters JAVA  (0) 2022.12.16
[LeetCode] 002. Add Two Numbers JAVA  (0) 2022.12.16
[LeetCode] 001. Two Sum JAVA  (0) 2022.12.15

๋Œ“๊ธ€