【leetCode】5_최장 메모 문자열

1181 단어 leetCode
class Solution {
    public String longestPalindrome(String s) {
        int maxLength = 0, ti = 0, tj = 1;
        int strlen = s.length();
        int[][] dp = new int[strlen + 5][strlen + 5];
        for (int i = 0; i < strlen; i ++){
            for (int j = 0; j < 2; j ++){
                dp[i][i + j] = 1;
            }
        }
        for (int i = 1; i < strlen; i ++){
            dp[i][i - 1] = 1;
        }
        for(int k = 1; k <= strlen; k ++){
            for (int i = 0; i < strlen; i ++){
                if (i + k > strlen)
                    break;
                if (s.charAt(i) == s.charAt(i + k - 1)){
                    dp[i][k + i] = dp[i + 1][i + k - 1];
                    if ((dp[i][k + i] == 1) && (k > maxLength)) {
                        maxLength = k;
                        tj = k + i;
                        ti = i;
                    }
                }
                else{
                    dp[i][i + k] = 0;
                }

            }
        }

        if (strlen != 0)
            return s.substring(ti, tj);
        else
            return "";
    }
}

좋은 웹페이지 즐겨찾기