LeetCode中的动态规划问题(一)

Regular Expression Matching

Problem description:

Implement regular expression matching with support for ‘.‘ and ‘*‘.

‘.‘ Matches any single character.
‘*‘ Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

解题思路:

不是显式DP问题(保存一张表),用Recursion的思路可解。

1)若p[j+1] != ‘*‘,那么判断p[j]和s[i]的结果就可以了。

  p[j]==s[i]或者p[j]==‘.‘,到当前位置是匹配的,继续向下判断;不满足条件,说明当前位置不匹配。

2)若p[j+1]==‘*‘,那么需要循环判断p[j+2]和s[i...n]是否匹配.

代码如下:

 1 class Solution {
 2 public:
 3     bool isMatch(const char *s, const char *p) {
 4          if(*p == 0)
 5             return *s == 0;
 6
 7         if(*(p+1) != ‘*‘)
 8         {
 9             if(*s != 0 && (*p == *s || *p == ‘.‘))
10                 return isMatch(s+1, p+1);
11             else
12                 return false;
13         }
14         else
15         {
16             while(*s != 0 && (*p == *s || *p == ‘.‘))
17             {
18                 if(isMatch(s, p+2))
19                     return true;
20
21                 s++;
22             }
23             return isMatch(s, p+2);
24         }
25     }
26 };

Longest Valid Parentheses

Problem description:

Given a string containing just the characters ‘(‘ and ‘)‘, find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

解题思路:

不是用DP解决的,用stack解决。使用pair<char, int>保存字符和位置。

1)如果s[i]==‘(‘,则压入栈;

2)如果s[i]==‘)‘,则判断st.top()是否是‘(‘,如果是则弹出栈;否则压入栈。

代码如下:

 1 class Solution {
 2 public:
 3     int longestValidParentheses(string s) {
 4         stack<pair<char,int> > st;
 5         int len = s.length();
 6
 7         if(len <= 1)
 8             return 0;
 9
10         pair<char,int> start(‘)‘,-1);
11         st.push(start);
12         int res = 0;
13         for(int i = 0; i < len; ++i)
14         {
15             if(s[i] == ‘(‘)
16             {
17                 pair<char,int> node(s[i],i);
18                 st.push(node);
19             }
20             else
21             {
22                 pair<char,int> top = st.top();
23                 if(top.first == ‘(‘)
24                 {
25                     st.pop();
26                     res = max(res, i-st.top().second);
27                 }
28                 else
29                 {
30                     pair<char,int> node(s[i],i);
31                     st.push(node);
32                 }
33
34             }
35         }
36
37         return res;
38     }
39 };

时间: 2024-08-26 06:46:18

LeetCode中的动态规划问题(一)的相关文章

LeetCode总结 -- 一维动态规划篇

这篇文章的主题是动态规划, 主要介绍LeetCode中一维动态规划的题目, 列表如下: Climbing Stairs Decode Ways Unique Binary Search Trees Maximum Subarray Maximum Product Subarray Best Time to Buy and Sell Stock 在介绍上述具体题目之前, 我们先说说动态规划的通常思路. 动态规划是一种算法思路(注意这里不要和递归混淆, 事实上递归和迭代只是两种不同的实现方法, 并不

动态规划以及在leetcode中的应用

之前只是知道动态规划是通过组合子问题来解决原问题的,但是如何分析,如何应用一直都是一头雾水.最近在leetcode中发现有好几道题都可以用动态规划方法进行解决,就此做下笔录. 动态规划:应用于子问题重叠情况,原问题的多个子问题间可能含有相同的子子问题,当然,关于将原问题分解成子问题的思路,分治算法也是可行的,但是如果采用分治递归来解决就会出现一些问题.在重复的子问题的计算中,分治算法会忽略到重复问题,也就是说相同的问题,分治算法会计算多次,这样效率会很低.而动态规划算法会仔细安排求解顺序,对每个

leetcode中一些要用到动态规划的题目

需要仔细回顾的题目: 1.Interleaving String   交叉存取字符串 2.Decode Ways   字符串解码 3.Subsets   Subsets II          求一个集合的幂集 leetcode中一些要用到动态规划的题目,布布扣,bubuko.com

Leetcode中字符串总结

本文是个人对LeetCode中字符串类型题目的总结,纯属个人感悟,若有不妥的地方,欢迎指出. 一.有关数字 1.数转换 题Interger to roman和Roman to integer这两题是罗马数字和整数之间的相互转换,首先要懂得什么是罗马数字以及相应的组数规则.LeetCode的题中给出的数字最大的是3999,.针对第一题有两种解法:第一是列举出罗马数字在个十百千上的各种情况,形成一个二维矩阵,然后对整数不停的取余.除10来确定相应的罗马数字:第二种是先列出罗马数字组成情况,然后通过从

leetcode中第一题twosum问题解答算法的可行性证明

leetcode中第一题twosum问题解答算法的可行性证明 一.引入 关于leetcode中第一题twosum问题,网上已有不少高人做出过解答,并提出了切实可行的算法实现.我在解答该题时参考了博客http://www.zixue7.com/article-9576-1.html的解答.为让读者更直观地阅读和理解本文,先简要摘录以上博客的内容如下: 题目还原 Two Sum Given an array of integers, find two numbers such that they a

leetcode中关于树的dfs算法题

Validate Binary Search Tree Recover Binary Search Tree Symmetric Tree Same Tree Maximum Depth of Binary Tree Construct Binary Tree from Preorder and Inorder Traversal Construct Binary Tree from Inorder and Postorder Traversal Convert Sorted Array to

LeetCode202:Happy Number 。C#版,在vs2010中通过,leetcode中Wrong Answer

static List<int> nums = new List<int>(); public static bool IsHappy(int n) { int newint = 0; while (n != 0) { newint += ((n % 10) * (n % 10)); n = n / 10; } if (newint == 1) return true; if (nums.Contains(newint)) { return false; } else { nums

用Javascript方式实现LeetCode中的算法(更新中)

前一段时间抽空去参加面试,面试官一开始让我做一道题,他看完之后,让我回答一下这个题的时间复杂度并优化一下,当时的我虽然明白什么是时间复杂度,但不知道是怎么计算的,一开局出师不利,然后没然后了,有一次我逛博客园时看到有个博主的文章说到有LeetCode这玩意,于是就知道了LeetCode.忽然有一种疑问:前端学不学算法?我看过一篇博文:为什么我认为数据结构与算法对前端开发很重要? 我觉得,前端应该是要学一下算法的,不久后前端明朗化,要做的工作量不低于后端人员,到时候也会像优化页面一样去优化js,既

LeetCode -- Word Break 动态规划,详细理解

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict = ["leet", "code"]. Return true because