[LeetCode] 678. Valid Parenthesis String 验证括号字符串
Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules:
- Any left parenthesis
'('
must have a corresponding right parenthesis')'
. - Any right parenthesis
')'
must have a corresponding left parenthesis'('
. - Left parenthesis
'('
must go before the corresponding right parenthesis')'
. '*'
could be treated as a single right parenthesis')'
or a single left parenthesis'('
or an empty string.- An empty string is also valid.
Example 1:
Input: "()"
Output: True
Example 2:
Input: "(*)"
Output: True
Example 3:
Input: "(*))"
Output: True
Note:
- The string size will be in the range [1, 100].
判断给定的字符串的括号匹配是否合法, 20. Valid Parentheses 的变形,这题里只有小括号'()'和*,*号可以代表'(', ')'或者相当于没有。
解法1: 迭代
解法2: 递归,最容易想到的解法,用一个变量cnt记录左括号的数量,当遇到*号时分为三种情况递归下去。Python TLE, C++: 1148 ms
解法2: 最优解法,设两个变量cmin和cmax,cmin最少左括号的情况,cmax表示最多左括号的情况,其它情况在[cmin, cmax]之间。遍历字符串,遇到左括号时,cmin和cmax都自增1;当遇到右括号时,当cmin大于0时,cmin才自减1,否则保持为0(因为其它*情况可能会平衡掉),而cmax减1;当遇到星号时,当cmin大于0时,cmin才自减1(当作右括号),而cmax自增1(当作左括号)。如果cmax小于0,说明到此字符时前面的右括号太多,有*也无法平衡掉,返回false。当循环结束后,返回cmin是否为0。
Java:
public boolean checkValidString(String s) {
int low = 0;
int high = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
low++;
high++;
} else if (s.charAt(i) == ')') {
if (low > 0) {
low--;
}
high--;
} else {
if (low > 0) {
low--;
}
high++;
}
if (high < 0) {
return false;
}
}
return low == 0;
}
Python:
class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
lower, upper = 0, 0 # keep lower bound and upper bound of '(' counts
for c in s:
lower += 1 if c == '(' else -1
upper -= 1 if c == ')' else -1
if upper < 0: break
lower = max(lower, 0)
return lower == 0 # range of '(' count is valid
Python:
def checkValidString(self, s):
cmin = cmax = 0
for i in s:
if i == '(':
cmax += 1
cmin += 1
if i == ')':
cmax -= 1
cmin = max(cmin - 1, 0)
if i == '*':
cmax += 1
cmin = max(cmin - 1, 0)
if cmax < 0:
return False
return cmin == 0
Python:
def checkValidString(self, s):
cmin = cmax = 0
for i in s:
cmax = cmax-1 if i==')' else cmax+1
cmin = cmin+1 if i=='(' else max(cmin - 1, 0)
if cmax < 0: return False
return cmin == 0
Python: TLE
class Solution(object):
def checkValidString(self, s):
"""
:type s: str
:rtype: bool
"""
return self.helper(s, 0) def helper(self, s, count):
# if not s:
# return count == 0
if count < 0:
return False for i in xrange(len(s)):
if s[i] == '(':
count += 1
elif s[i] == ')':
if count <= 0:
return False
else:
count -= 1
else:
return self.helper(s[i+1:], count+1) or \
self.helper(s[i+1:], count) or \
self.helper(s[i+1:], count-1) return count == 0 if __name__ == '__main__':
print Solution().checkValidString("(((((*(()((((*((**(((()()*)()()()*((((**)())*)*)))))))(())(()))())((*()()(((()((()*(())*(()**)()(())")
C++:
class Solution {
public:
bool checkValidString(string s) {
stack<int> left, star;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '*') star.push(i);
else if (s[i] == '(') left.push(i);
else {
if (left.empty() && star.empty()) return false;
if (!left.empty()) left.pop();
else star.pop();
}
}
while (!left.empty() && !star.empty()) {
if (left.top() > star.top()) return false;
left.pop(); star.pop();
}
return left.empty();
}
};
C++:
class Solution {
public:
bool checkValidString(string s) {
return helper(s, 0, 0);
}
bool helper(string s, int start, int cnt) {
if (cnt < 0) return false;
for (int i = start; i < s.size(); ++i) {
if (s[i] == '(') {
++cnt;
} else if (s[i] == ')') {
if (cnt <= 0) return false;
--cnt;
} else {
return helper(s, i + 1, cnt) || helper(s, i + 1, cnt + 1) || helper(s, i + 1, cnt - 1);
}
}
return cnt == 0;
}
};
C++:
class Solution {
public:
bool checkValidString(string s) {
int low = 0, high = 0;
for (char c : s) {
if (c == '(') {
++low; ++high;
} else if (c == ')') {
if (low > 0) --low;
--high;
} else {
if (low > 0) --low;
++high;
}
if (high < 0) return false;
}
return low == 0;
}
};
类似题目:
[LeetCode] 20. Valid Parentheses 合法括号
All LeetCode Questions List 题目汇总
[LeetCode] 678. Valid Parenthesis String 验证括号字符串的更多相关文章
- [LeetCode] Valid Parenthesis String 验证括号字符串
Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...
- [leetcode]678. Valid Parenthesis String验证有效括号字符串
Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...
- leetcode 678. Valid Parenthesis String
678. Valid Parenthesis String Medium Given a string containing only three types of characters: '(', ...
- 【LeetCode】678. Valid Parenthesis String 解题报告(Python)
[LeetCode]678. Valid Parenthesis String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人 ...
- 678. Valid Parenthesis String
https://leetcode.com/problems/valid-parenthesis-string/description/ 这个题的难点在增加了*,*可能是(也可能是).是(的前提是:右边 ...
- 【leetcode】Valid Parenthesis String
题目: Given a string containing only three types of characters: '(', ')' and '*', write a function to ...
- [LeetCode] 680. Valid Palindrome II 验证回文字符串 II
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a pa ...
- [Swift]LeetCode678. 有效的括号字符串 | Valid Parenthesis String
Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...
- LeetCode Valid Parenthesis String
原题链接在这里:https://leetcode.com/problems/valid-parenthesis-string/description/ 题目: Given a string conta ...
随机推荐
- 51nod 1254 最大子段和 V2
N个整数组成的序列a[1],a[2],a[3],…,a[n],你可以对数组中的一对元素进行交换,并且交换后求a[1]至a[n]的最大子段和,所能得到的结果是所有交换中最大的.当所给的整数均为负数时和为 ...
- robot framework 笔记(三),RF安装
背景: 本来robot framework的安装应该放在一开始写的,因写博客的时候已经装过了,恰巧重装系统又重装了一遍RF RF推荐使用python2, 使用3的话会遇到一些页面非友好的问题 需要的安 ...
- c++中关联容器map的使用
C++关联容器<map>简单总结(转) 补充: 使用count,返回的是被查找元素的个数.如果有,返回1:否则,返回0.注意,map中不存在相同元素,所以返回值只能是1或0. 使用find ...
- 爬虫 - 请求库之requests
介绍 使用requests可以模拟浏览器的请求,比起python内置的urllib模块,requests模块的api更加便捷(本质就是封装了urllib3) 注意:requests库发送请求将网页内容 ...
- volatile 错误示范做线程同步 demo
这里 http://hedengcheng.com/?p=725 有对volatile 非常详细的解释,看完之后,心里一惊,因为我刚好在一个项目里用了文中错误示范那种方式来做线程同步,场景如下: Th ...
- 算法笔记求序列A每个元素左边比它小的数的个数(树状数组和离散化)
#include <iostream> #include <algorithm> #include <cstring> using namespace std ; ...
- vuex 之既生‘mutation’何生‘action’
vuex 中,action 及 mutation 均为操作数据的作用而存在,既然二者均可改变数据,为什么要分成两个方法来处理呢,因为: Mutation 必须是同步函数 mutations: { so ...
- something about 乘法逆元
before 在求解除法取模问题(a / b) % m时,我们可以转化为(a % (b * m)) / b, 但是如果b很大,则会出现爆精度问题,所以我们避免使用除法直接计算. (逆元就像是倒数一样的 ...
- [HAOI2015]树上染色 树状背包 dp
#4033. [HAOI2015]树上染色 Description 有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并 将其他的N-K个点染成白 ...
- 原创:logistic regression实战(一):SGD Without lasso
logistic regression是分类算法中非常重要的算法,也是非常基础的算法.logistic regression从整体上考虑样本预测的精度,用判别学习模型的条件似然进行参数估计,假设样本遵 ...