DP on String

public boolean wordBreak(String s, List<String> wordDict) {
    boolean[] dp = new boolean[s.length() + 1];
    dp[0] = true;
    for (int i = 1; i <= s.length(); i++) {
        for (String w : wordDict) {
            if (i - w.length() >= 0 
                && s.substring(i - w.length(), i).equals(w) 
                && dp[i - w.length()]) {
                dp[i] = true;
            }
        }
    }
    return dp[s.length()];
}

Q: the total number of ways to decode it.

dp[i] : the total number of ways to decode at i:

  • dp[0] = 1

  • dp[1] = 0 when "02" situation, dp[1] = 1 when other situation.

Transition: dp[i] = dp[i - 1] + dp[i - 2];

dp[i][j] : longest common subsequence ends at i in text1, j in text2

if s.charAt(i) == t.charAt(j) : dp[i][j] = dp[i - 1][j - 1] + 1

else: dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1])

The question asks the minimum number of deletion to make word1 and word2 the same, this means to get Longest Common Subsequence of two strings and use the total lens - LCS:

dp[i][j] : maximum length of common subarray up to i and j

if (A[i] == B[j]) { dp[i][j] = dp[i - 1][j - 1] + 1; }

when s.charAt(i) != t.charAt(j):

  • insert = dp[i][j] = dp[i - 1][j] + 1

  • delete = dp[i][j] = dp[i][j - 1] + 1

  • replace = dp[i][j] = dp[i - 1][j - 1] + 1

dp[i][j] : the starting index of the substring where T has length i and S has length j.

if s.charAt(i) == t.charAt(j), dp[i][j] = dp[i - 1][j - 1]

else: dp[i][j] = dp[i - 1][j]

After find all starting indices, go through then and then length of the window is i - dp[i][n].

Palindrome

dp[i][j] = dp[i + 1][j - 1] + 2 when s.charAt(i) == s.charAt(j)

dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]) when s.charAt(i) != s.charAt(j)

132. Palindrome Partitioning II

cut[R] is the minimum of cut[L - 1] + 1 (L <= R), if [L, R] is palindrome.

If [L, R] is palindrome, [L + 1, R - 1] is palindrome, and c[L] == c[R].

Find how many palindromic subsequences (need not necessarily be distinct) can be formed in a given string. Note that the empty string is not considered as a palindrome.

Examples:

Input : str = "abcd"

Output : 4

Explanation :- palindromic subsequence are : "a" ,"b", "c" ,"d"

Input : str = "aab"

Output : 4

Explanation :- palindromic subsequence are :"a", "a", "b", "aa"

Input : str = "aaaa"

Output : 15

Initial Values : i= 0, j= n-1;

CountPS(i,j): Every single character of a string is a palindrome subsequence

if i == j: return 1 // palindrome of length 1

// If first and last characters are same, then we consider it as palindrome subsequence and checkfor the rest subsequence (i+1, j), (i, j-1)

Else if (str[i] == str[j)]: return countPS(i+1, j) + countPS(i, j-1) + 1;

Last updated

Was this helpful?