This is the typical DP problem, the time complexity is O(n2), Where n is the length of string s. This is due to the fact that we try to find result for all combinations of l and r where l and r range from 0 to n:

    private int[][] visited;
    public boolean isValidPalindrome(String s, int k) {
        if (s == null || s.length() == 0)
            return true;
        int n = s.length();
        visited = new int[n][n];
        return helper(s, 0, n - 1) <= k;
    }

    private int helper(String s, int l, int r) {
        if (r <= l)
            return 0;
        if (visited[l][r] > 0)
            return visited[l][r];
        if (s.charAt(l) == s.charAt(r)) {
            visited[l][r] = helper(s, l + 1, r - 1);
        } else {
            visited[l][r] = 1 + Math.min(helper(s, l, r - 1), helper(s, l + 1, r));
        }
        return visited[l][r];
    }

 

posted on 2022-02-03 00:47  阳光明媚的菲越  阅读(19)  评论(0编辑  收藏  举报