끄적끄적

[알고리즘] Longest Palindromic Substring (java) 본문

Computer Science/Algorithm

[알고리즘] Longest Palindromic Substring (java)

mashko 2020. 4. 25. 20:17
반응형

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || "".equals(s)) {
            return s;
        }

        int len = s.length();
        int max = 0;
        String answer = "";

        boolean[][] dp = new boolean[len][len];

        for (int j = 0; j < len; j++) {

            for (int i = 0; i <= j; i++) {

                boolean judge = s.charAt(i) == s.charAt(j);

                dp[i][j] = j - i > 2 ? dp[i + 1][j - 1] && judge : judge;

                if (dp[i][j] && j - i + 1 > max) {
                    max = j - i + 1;
                    answer = s.substring(i, j + 1);
                }
            }
        }

        return answer;
    }
}


Runtime - 333 ms
Memory - 65.8 MB

반응형
Comments