[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 ...
随机推荐
- zookeeper题目
1. ZooKeeper是什么?2. ZooKeeper提供了什么?3. Zookeeper文件系统4. ZAB协议?5. 四种类型的数据节点 Znode6. Zookeeper Watcher 机制 ...
- C# 获取操作系统空闲时间
获取系统鼠标和键盘没有任何操作的空闲时间 public class CheckComputerFreeState { /// <summary> /// 创建结构体用于返回捕获时间 /// ...
- SQL中的trim函数
Oracle TRIM函数是很常见的函数,下面对Oracle TRIM函数的语法作了详尽的阐述说明,希望可以让您对Oracle TRIM函数有更深的认识. 如果提到Oracle TRIM函数,最简单的 ...
- 【深入ASP.NET原理系列】--Asp.Net Mvc和Asp.Net WebForm实际上共用一套ASP.NET请求管道
.NET FrameWork4在系统全局配置文件(如在如下目录中C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config) 中添加了一个名字叫Url ...
- pass的作用?
1.空语句 do nothing 2.保证格式完整,保证语义完整 3.占位语句
- jmeter使用教程
jmeter是基于JVM(最新版本基于jdk8+)的压测工具包.提供了丰富的工具来设置压测计划,执行压测任务和生成压测报告. 我这边使用的是windows10平台. 整个流程如下: 1.下载jmete ...
- 洛谷P1270 访问美术馆
题目 树形DP,首先考虑递归建图,类似于线段树的中序遍历.然后取状态dp[i][j]表示i点花费j时间所偷到的最多的画,有方程: \(dp[now][nwt] = max(dp[now][nwt], ...
- gdb 调试core文件报错: in free () from /lib64/libc.so.6 找不到原因啊
运行程序死掉 找不到原因啊..gdb 跟踪与堆栈信息 贴出来了 麻烦大佬们看一下,给个回复,不胜感激!! Core was generated by `./scene_s0037 10037'.Pr ...
- 第12组 Beta冲刺(4/5)
Header 队名:To Be Done 组长博客 作业博客 团队项目进行情况 燃尽图(组内共享) 展示Git当日代码/文档签入记录(组内共享) 注: 由于GitHub的免费范围内对多人开发存在较多限 ...
- cpu指令重排序的原理
目录: 1.重排序场景 2.追根溯源 3.缓存一致性协议 4.重排序原因 一.重排序场景 class ResortDemo { int a = 0; boolean flag = false; pub ...