[Leetcode] 5. Longest Palindromic Substring (JAVA)

유존돌돌이·2021년 9월 6일
0

Leetcode

목록 보기
12/17
post-thumbnail

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

Example 1:
Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
Example 3:
Input: s = "a"
Output: "a"
Example 4:
Input: s = "ac"
Output: "a"

Constraints

1 <= s.length <= 1000
s consist of only digits and English letters.

My Code

class Solution {
    public String longestPalindrome(String s) {
        String ret = "";
        for(int i=0 ; i<s.length() ; i++) {
            int len = Math.max(helper(s,i,i), helper(s,i,i+1));
            if(ret.length()<len) {
                ret = s.substring(i-(len-1)/2, i+len/2+1);
            }
        }
        return ret;
    }
    public int helper(String str, int s, int e) {
        if(s<0 || e>=str.length()) return 0;
        while(s>=0 && e<str.length() && str.charAt(s)==str.charAt(e)) {
            s--;
            e++;
        }
        return e-s-1;
    }
}

Comment

개념 간단한데 정말 몇번 반복해서 풀었던 문제.

0개의 댓글