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:

  1. Any left parenthesis '(' must have a corresponding right parenthesis ')'.
  2. Any right parenthesis ')' must have a corresponding left parenthesis '('.
  3. Left parenthesis '(' must go before the corresponding right parenthesis ')'.
  4. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string.
  5. An empty string is also valid.

Example 1:

Input: "()"
Output: True

Example 2:

Input: "(*)"
Output: True

Example 3:

Input: "(*))"
Output: True

Note:

  1. 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 验证括号字符串的更多相关文章

  1. [LeetCode] Valid Parenthesis String 验证括号字符串

    Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...

  2. [leetcode]678. Valid Parenthesis String验证有效括号字符串

    Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...

  3. leetcode 678. Valid Parenthesis String

    678. Valid Parenthesis String Medium Given a string containing only three types of characters: '(', ...

  4. 【LeetCode】678. Valid Parenthesis String 解题报告(Python)

    [LeetCode]678. Valid Parenthesis String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人 ...

  5. 678. Valid Parenthesis String

    https://leetcode.com/problems/valid-parenthesis-string/description/ 这个题的难点在增加了*,*可能是(也可能是).是(的前提是:右边 ...

  6. 【leetcode】Valid Parenthesis String

    题目: Given a string containing only three types of characters: '(', ')' and '*', write a function to ...

  7. [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 ...

  8. [Swift]LeetCode678. 有效的括号字符串 | Valid Parenthesis String

    Given a string containing only three types of characters: '(', ')' and '*', write a function to chec ...

  9. LeetCode Valid Parenthesis String

    原题链接在这里:https://leetcode.com/problems/valid-parenthesis-string/description/ 题目: Given a string conta ...

随机推荐

  1. 【转载】lr运行时设置,每个action 比例

    提供了再脚本运行时所需要的相关选项. 性能测试的关键之一:能否通过脚本来完全模拟用户的行为,可以通过运行设置让脚本运行的更人性化. 1. Run Logic 脚本如何运行,每个action与actio ...

  2. Linux入侵类问题排查思路

    深入分析,查找入侵原因 一.检查隐藏帐户及弱口令 检查服务器系统及应用帐户是否存在 弱口令: 检查说明:检查管理员帐户.数据库帐户.MySQL 帐户.tomcat 帐户.网站后台管理员帐户等密码设置是 ...

  3. .NET Core项目修改project.json来引用其他目录下的源码等文件的办法 & 解决多框架时 project.json 与 app.config冲突的问题

    作者: zyl910 一.缘由 项目规模大了后,经常会出现源码文件分布在不同目录的情况,但.NET Core项目默认只有项目目录下的源码文件,且不支持“Add As Link”方式引入文件.这时需要手 ...

  4. Centos7-安装py3

    安装依赖 yum install gcc openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel li ...

  5. Alpha冲刺(7/10)——2019.4.30

    所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(7/10)--2019.4.30 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...

  6. Centos7 yum安装postgresql 9.5

    添加RPM yum install https://download.postgresql.org/pub/repos/yum/9.5/redhat/rhel-7-x86_64/pgdg-centos ...

  7. windows查看端口被占用情况

    首先,使用cmd命令打开CMD命令窗口 使用下面的命令来查看某端口被占用的情况,以8035为例: netstat -ano|findstr " 结果如下图: 最后一列的6532为PID号,根 ...

  8. *arg和**kwarg作用

    *args:可以理解为只有一列的表格,长度不固定. **kwargs:可以理解为字典,长度也不固定. 1.函数调用里的*arg和**kwarg:              (1) *arg:元组或列表 ...

  9. Redis存储Set

    与List不同Set不能存储相同元素,且数据没有顺序. 存储结构: 1.存储与查看数据: 2.删除指定的一个元素: 3.判断是否存在某一个元素(存在返回1,不存在返回0): 4.判断两个set中的特有 ...

  10. P5589 【小猪佩奇玩游戏】

    这题还是比较妙妙套路的,复杂度为\(O(log^2N)\),可以卡掉\(\sqrt n\)的做法 首先我们可以把原数列分成很多个集合,集合之间肯定是两两独立的,考虑分别计算答案 我们定义\(f_i\) ...