Algorithm-week16
来源:互联网 发布:逆袭网络剧06在线观看 编辑:程序博客网 时间:2024/06/05 00:16
Week16
Problem--Medium--392. Is Subsequence
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace"
is a subsequence of "abcde"
while "aec"
is not).
Example 1:
s = "abc"
, t = "ahbgdc"
Return true
.
Example 2:
s = "axc"
, t = "ahbgdc"
Return false
.
题目解析:
这道题目可以用动态规划算法进行求解,首先,我们需要将问题划分出其子问题,也就是前状态是什么,我们求解两段不同长度m,n字符串是否为子串关系,其前状态可以分为求解长度为m-1,n-1的字符串是否为子串关系。所以我们可以直观定义dp[i][j]为长度为i,j的字符串是否为子串关系,这个关系不是单纯的真假关系,而是两者最长的公共子字符串的长度,这样我们在最后只需判断dp[m][n]是否等于s的长度即可。优化后,状态数组可以变为一维数组。
定义状态:
dp[i][j]为长度为i的字符串s与长度为j的字符串t最长公共子字符串长度。
状态转移:
if (s[i - 1] == t[j - 1]): dp[i][j] = dp[i - 1][j - 1] + 1;
else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])
优化后:
状态变量可变为dp[i],因为每次更新之后只会用到上一次更新的值,没必要保留所有i更新的值,所以我们保存一次更新值即可,在下次更新中用自己的旧值进行更新。
代码:
class Solution {public: bool isSubsequence(string s, string t) { vector<int> dp(t.length() + 1, 0); for (int i = 1; i <= s.length(); i++) { for (int j = 1; j <= t.length(); j++) { if (s[i - 1] == t[j - 1]) { dp[j] = min(dp[j - 1] + 1, i); //cout << s[i - 1] << " " << dp[j] << endl; } else { dp[j] = max(dp[j - 1], dp[j]); } //cout << dp[j] << endl; } } if (dp[t.length()] == s.length()) { return true; } else { return false; } }};
简单方法:
其实这道题根本不需要用动态规划来做,LeetCode上分类是动态规划所以引导别人用动态规划做。最简单的方法其实只需遍历t字符串,遇到与s相同字符的s的指针前进一,最后判断s的指针是否直到字符串尾即可。
代码:
class Solution {public: bool isSubsequence(string s, string t) { int pos = 0; for (int i = 0; i < t.length(); i++) { if (t[i] == s[pos]) { pos++; } } return pos == s.length(); }};
- Algorithm-week16
- week16
- week16-09
- week16-10
- week16-11
- Leetcode Week16
- leetcode week16
- Week16 总结
- 【算法设计作业】week16
- LeetCode题解 week16
- LeetCode Week16: Word Ladder II
- Algorithm
- Algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- algorithm
- 信贷分控的九个维度
- Tomcat部署的方式
- MATLAB中mean的用法
- 从零开始写聊天机器人
- Git安装配置
- Algorithm-week16
- 运算符重载的俩边为不同类的对象
- 菜鸟学习之路------学习DNS的配置(LINUX)
- BZOJ1081(SCOI2005)[超级格雷码]--找规律+暴搜
- 多种方法模拟估计值(蒙特卡罗)
- 机器学习总结(二)——逻辑斯谛回归和最大熵模型
- 机器学习算法工程师面试总结
- MVC学习笔记四:利用Entity Framework调用存储过程
- Graphviz入门