678. Valid Parenthesis String
Posted lyinfo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了678. Valid Parenthesis String相关的知识,希望对你有一定的参考价值。
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].
看到题目后,有印象曾经也在leetcode做过括号配对的题目,但是这题比较难处理的是‘*’号,作为任意匹配字符,既可以消耗一个‘)’号,也可以作为无用字符。思考一会后,基本确定思路:
1、使用stack,入栈‘(’和‘*’号,在遇到‘)‘时,出栈(’和‘*’号;
2、出栈过程中优先消耗左括号,实在没有对应的左括号时,消耗一个离栈顶最近的星号;
3、从栈顶开始找左括号的过程中,如果找到对应的做左括号,要把寻找过程中出栈的星号再次压回栈中。
具体代码如下,要注意栈中无元素的情况下,继续出栈,会报ArrayIndexOutOfBoundsException异常:
public static void main(String[] args) { // String s = "((*)" String s = "(((******))"; // String s = "(())((())()()(*)(*()(())())())()()((()())((()))(*"; System.out.println(checkValidString(s)); } public static boolean checkValidString(String s) { Stack<Character> chars = new Stack<>(); int countStart = 0; for (int i = 0; i < s.length(); i++) { char curr = s.charAt(i); if (‘(‘ == curr || ‘*‘ == curr) { chars.push(curr); } else if (‘)‘ == curr) { if (chars.size() == 0) { return false; } countStart = 0; while (!chars.isEmpty() && chars.peek() == ‘*‘) { chars.pop(); countStart++; } if (!chars.isEmpty()) { chars.pop(); while (countStart-- > 0) { chars.push(‘*‘); } } else if (countStart > 0) { int temp = countStart - 1; while (temp-- > 0) { chars.push(‘*‘); } } else { return false; } } } if (chars.isEmpty()) { return true; } else { countStart = 0; while (!chars.isEmpty()) { char a = chars.pop(); if (‘(‘ == a) { if (countStart > 0) { countStart--; } else { return false; } } else { countStart++; } } } return true; }
以上是关于678. Valid Parenthesis String的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Valid Parenthesis String 验证括号字符串
leetcode 20. Valid Parentheses