当前位置:网站首页>Dynamic programming problem (VII)
Dynamic programming problem (VII)
2022-07-29 00:21:00 【std i hurt o love】
One 、 Regular Expression Matching
solution : Dynamic programming
If it's only lowercase , Then directly compare whether the characters are the same to match , If there is one more ’.‘, You can use it to match any character , As long as it corresponds to str If the element in is not empty . But more ’*' character , There are many situations , Involving state transition , So we use dynamic programming .
set up dp[i][j] Express str front i Characters and pattern front j Whether characters match .( You need to pay attention to the i,j It's length. , More than the corresponding string subscripts 1)
First , Beyond all doubt , Two empty strings are directly matched , therefore dp[0][0]=true. Then we assume str The string is empty , that pattern How can I match an empty string ? The answer is to use ’‘ The character appears 0 Secondary characteristics . Traverse pattern character string , If you encounter ’' It means that the characters in front of it can appear 0 Time , To match an empty string, there can only be 0, That's equivalent to considering whether the previous character can match , therefore dp[0][i]=dp[0][i−2].
Then traverse str And pattern Each length of , Start looking for state transitions . First, consider that the character is not ’‘ Simple situation of , As long as the two characters traversed are equal , or pattern In the string is ’.‘ To match , So the last bit matches , That is, check whether the previous one of the two can complete the matching , namely dp[i][j]=dp[i−1][j−1]. Then consider ’' What happened :
pattern[j - 2] == ‘.’ || pattern[j - 2] == str[i - 1]: namely pattern The previous one can match one more , It can be used ’*' Let it appear one more time or not , So there's a transfer equation dp[i][j]=dp[i−1][j]∣∣dp[i][j−2]
Not meeting the above conditions , Can only not match , Let the previous character appear 0 Time ,dp[i][j]=dp[i][j−2].
class Solution {
public:
bool match(string str, string pattern) {
int n1 = str.length();
int n2 = pattern.length();
//dp[i][j] Express str front i Characters and pattern front j Whether characters match
vector<vector<bool> > dp(n1 + 1, vector<bool>(n2 + 1, false));
// Both are empty strings and naturally match
dp[0][0] = true;
// initialization str Empty situation , String subscript from 1 Start
for(int i = 2; i <= n2; i++){
// You can repeat the first character of yourself 0 Time
if(pattern[i - 1] == '*')
// It is related to the previous one that can match the empty string
dp[0][i] = dp[0][i - 2];
}
// Traverse str Each length
for(int i = 1; i <= n1; i++){
// Traverse pattern Each length
for(int j = 1; j <= n2; j++){
// The current character is not *, use . To match or match characters directly
if(pattern[j - 1] != '*' && (pattern[j - 1] == '.' || pattern[j - 1] == str[i - 1])){
dp[i][j] = dp[i - 1][j - 1];
// The current character is *
}else if(j >= 2 && pattern[j - 1] == '*'){
// If the previous one is . Or the previous digit can match this number
if(pattern[j - 2] == '.' || pattern[j - 2] == str[i - 1])
// Transfer situation
dp[i][j] = dp[i - 1][j] || dp[i][j - 2];
else
// Mismatch
dp[i][j] = dp[i][j - 2];
}
}
}
return dp[n1][n2];
}
};
Time complexity :O(mn), among m and n Respectively, the length of string and template string , Initialize ergodic matrix side , The state transition traverses the entire dp matrix
Spatial complexity :O(mn), Array aided dynamic programming dp Space
Two 、 Longest bracket substring
Solution 1 : Stack ( recommend )
- You can use the stack to record the left parenthesis subscript .
- Traversal string , Left bracket in stack , Each time the right bracket is encountered, the subscript of the left bracket will pop up .
- Then the length is updated to the distance between the current subscript and the subscript at the top of the stack .
- Inconsistent parentheses encountered , May make the stack empty , So you need to use start Record the last ending position , This subtracts from the current subscript start You can get the length , The substring is obtained .
- The maximum length of the last maintained substring in the loop .
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0;
// Record the last position where consecutive parentheses ended
int start = -1;
stack<int> st;
for(int i = 0; i < s.length(); i++){
// Left bracket in stack
if(s[i] == '(')
st.push(i);
// Right bracket
else{
// If the stack is empty when closing the parenthesis , illegal , Set to end position
if(st.empty())
start = i;
else{
// Pop up the left bracket
st.pop();
// There are also left parentheses in the stack , The right bracket is not enough , Subtracting the top of the stack is the length
if(!st.empty())
res = max(res, i - st.top());
// There are no parentheses in the stack , Explain the line numbers in the left and right brackets , Subtracting the last ending position is the length
else
res = max(res, i - start);
}
}
}
return res;
}
};
Time complexity :O(n), among n Is the length of a string , Traversing the entire string
Spatial complexity :O(n), At worst, it's all left parentheses , The stack size is n
Solution 2 : Dynamic programming
use dp[i] Indicates that the following is marked as i The character of is the longest legal bracket length of the end point .
It's obvious that the left parenthesis can't be the end , So the left parentheses are all dp[i]=0.
We traverse the string , Because the first place is either the left bracket or the right bracket dp Arrays are all 0, So skip , We will only look at the right parenthesis later , There are two cases of closing parentheses :
Situation 1 :
As shown in the figure , Next to the left bracket is the right bracket , Then the legal brackets need to be added 2, It is possible to add... On the basis before this pair of parentheses , Maybe this pair is the starting point , So the transfer formula is :dp[i]=(i>=2?dp[i−2]:0)+2Situation two :
As shown in the figure , The left bracket that matches the right bracket is not next to itself , But before the legal sequence before it , Therefore, the first matching left parenthesis can be obtained by subtracting the legal sequence length of the previous one from the subscript , So the transfer formula is :dp[i]=(i−dp[i−1]>1?dp[i−dp[i−1]−2]:0)+dp[i−1]+2Maintain the maximum value after each inspection .
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0;
// The length is 0 String of , return 0
if(s.length() == 0)
return res;
//dp[i] Indicates that the following is marked as i The character of is the longest legal bracket length of the end point
vector<int> dp(s.length(), 0);
// First, whether the left bracket or the right bracket is 0, So don't worry
for(int i = 1; i < s.length(); i++){
// Take the left bracket and mark it as 0, It is legal to have a right parenthesis
if(s[i] == ')'){
// If the previous position of the right bracket is the left bracket
if(s[i - 1] == '(')
// Count +2
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
// Find the first left parenthesis before this sequence of consecutive legal parentheses to match
else if(i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(')
dp[i] = (i - dp[i - 1] > 1 ? dp[i - dp[i - 1] - 2] : 0) + dp[i - 1] + 2;
}
// Maintenance maximum
res = max(res, dp[i]);
}
return res;
}
};
Time complexity :O(n), among n Is the length of a string , Traverse the string once
Spatial complexity :O(n), The length of dynamic programming auxiliary array is n
边栏推荐
- CV instance segmentation model sketch (1)
- 【MySQL系列】MySQL数据库基础
- Why is it so difficult for the SEC to refuse the application for transferring gray-scale GBTC to spot ETF? What is the attraction of ETF transfer?
- AutoCAD -- import excel tables into CAD and merge CAD
- Cmake basic learning
- MQ 消息丢失、重复、积压问题,如何解决?
- mysql中exists的用法详解
- Centos7 install mysql8
- [CNN] Why is the convolution kernel size of CNN usually odd
- 熊市下PLATO如何通过Elephant Swap,获得溢价收益?
猜你喜欢
Leetcode63. Different paths II
Leetcode59. Spiral matrix II
Real time data warehouse: Netease strictly selects the practice of real-time data warehouse based on Flink
研发效能的道法术器
【小程序项目开发 -- 京东商城】uni-app 商品分类页面(上)
【C】 Introduction and Simulation Implementation of ATOI and offsetof
MySQL安装配置教程(超级详细、保姆级)
Leetcode61. rotating linked list
centos7安装mysql8
Plato farm is expected to further expand its ecosystem through elephant swap
随机推荐
JS four formulas for judging data types
MySQL 分库分表及其平滑扩容方案
Advanced area of attack and defense world web masters unserialize3
#{}和${}的区别
Where is sandbox's confidence in rejecting meta's acquisition of meta universe leader sand?
html+css+php+mysql实现注册+登录+修改密码(附完整代码)
Es6操作教程
Develop effective Tao spell
递归/回溯刷题(中)
Eye of depth (18) -- partial derivative
Immutable x officially opens IMX token pledge detailed IMX pledge introduction optimistic about the development prospect of IMX
Principle of meter skipping
MySql中的like和in走不走索引
2022网络安全学习路线 非常详细 推荐学习
Leetcode64. Minimum path sum
Event extraction and documentation (2018)
Use hutool tool class to operate excel with more empty Sheet1
递归/回溯刷题(下)
动态规划问题(八)
How can Plato obtain premium income through elephant swap in a bear market?