今天闲来无事又刷了几道。
Longest Valid Parentheses
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.
class Solution {public: int longestValidParentheses(string &s) { if (s == "") return 0; int cnt = 0; int totr = 0; int lastValid = -1; for (int i = 0;i < s.length();i++) { if (s[i] == ')') totr++; cnt += (s[i] == '(' ? 1:-1); if (cnt < 0) { if (i+1 < s.length()) { s = s.substr(i+1,s.length()-i-1); return max(i,longestValidParentheses(s)); } else return i; } if (cnt == 0) lastValid = i; } if (lastValid > 0) { s = s.substr(lastValid+1,s.length()-lastValid-1); for (auto& x : s) x = (x=='('?')':'('); reverse(s.begin(),s.end()); return max(longestValidParentheses(s),lastValid + 1); } else { for (auto& x : s) x = (x=='('?')':'('); reverse(s.begin(),s.end()); return longestValidParentheses(s); } }};
只能说,我想歪了。这是道简单的DP,中间还WA了很多次。
我这个神奇的做法也是醉了。
比较需要引起注意的是,递归当中,如果带着数组字符串之类的,如果没有&,很容易MLE。
标准的做法是 f[i] 表示 i 结尾最长的合法序列,
如果(结尾, 0
如果()结尾, f[i-2]+2
如果))结尾, s[i - f[i-1] - 1]=='(' 的情况下 f[i-f[i-1]-2]+f[i-1]+2
11.17
想多了
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A =[2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
贪心
class Solution {public: int jump(vector & a) { int cl = 0; int cr = 0; int steps = 0; while (cl <= cr && cr < a.size() - 1) { int nr = cr; for (int i = cl;i<=cr;i++) nr = max(nr,i+a[i]); steps++; cl = cr+1; cr = nr; } return steps; }};