标签:hat HERE 问题 etc length ati string sub answer
Two Sequences 的题目一般会提供两个sequence,一般问最大/最小、true/false、count(*)这几类的问题。
其中,Two Sequences的动态规划题目的四要素:
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
题目中,提供了两个source string,一个目标string,问的也是true or false的问题,因此可以考虑two sequences的解法。
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s3.length() != s1.length() + s2.length()) { return false; }
// state dp[i][j] 表示s1的前i个字符 和 s2的前j个字符 能否组成s3的前(i + j) 个字符
boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];
// initialization
// dp[0][j] :s1的前0个字符 和 s2的前j个字符 能否组成 s3的前j个字符?
for (int j = 0; j < dp[0].length; j++) {
// 要判断两个字符串是否相等, 必须用字符串的equals方法来比较
dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j));
//dp[0][j] = s2.substring(0, j) == s3.substring(0, j); // 比较的是两个字符串的reference,并不是实际是否相等,因此这么写是错的
}
// dp[i][0] 同理
for (int i = 0; i < dp.length; i++) {
dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i));
//dp[i][0] = s1.substring(0, i) == s3.substring(0, i); // 错误
}
// function
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
dp[i][j] = (dp[i - 1][j] && (s1.charAt(i - 1) == s3.charAt(i + j - 1))) || (dp[i][j - 1] && (s2.charAt(j - 1) == s3.charAt(i + j - 1)));
}
}
// answer
return dp[s1.length()][s2.length()];
}
}
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example1Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example2
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
<LeetCode>动态规划——Two Sequences 类型题目
标签:hat HERE 问题 etc length ati string sub answer
原文地址:https://www.cnblogs.com/isguoqiang/p/11529981.html