Java写题解的第3天 | #密码截取#

密码截取

http://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1

问题等价于leetcode 第五题,可以参考leetcode的官方题解
https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zui-chang-hui-wen-zi-chuan-by-leetcode-solution/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s = "";
        while ((s = br.readLine()) != null) {
            System.out.println(validLen(s));
        }
        br.close();
    }

    public static int validLen(String s) {
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        for(int i = 0; i < len - 1; i++) {
            dp[i][i] = true;
            if (s.charAt(i) == s.charAt(i+1)) {
                dp[i][i+1] = true;
            }
        }
        for (int m = len - 2; m > -1; m--) {
            for (int n = m + 2; n < len; n++) {
                if (dp[m+1][n-1] && s.charAt(m) == s.charAt(n)) {
                    dp[m][n] = true;
                }
            }
        }
        int ans = 1;
        for (int p = 0; p < len; p++) {
            for (int q = p + 1; q < len; q++) {
                if (dp[p][q]) {
                    ans = (ans > q - p + 1)? ans: (q - p + 1);
                }
            }
        }
        return ans;
    }
}
全部评论

相关推荐

10-15 15:00
潍坊学院 golang
跨考小白:这又不是官方
投递拼多多集团-PDD等公司10个岗位
点赞 评论 收藏
分享
评论
2
8
分享
牛客网
牛客企业服务