LeetCode Valid Parenthesis String
2017-10-20 13:24
295 查看
原题链接在这里:https://leetcode.com/problems/valid-parenthesis-string/description/
题目:
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
Any right parenthesis
Left parenthesis
An empty string is also valid.
Example 1:
Example 2:
Example 3:
Note:
The string size will be in the range [1, 100].
题解:
计数"("的数目. 遇到"("加一. 遇到")" 减一.
遇到"*". 可能分别对应"(", ")"和empty string 三种情况. 所以计数可能加一, 减一或者不变. 可以记录一个范围[lo, hi].
lo维持在0或以上的位置.
但若是hi都小于0, 说明确定的")"更多, 直接返回false.
否则看最后lo能否能停在0.
Time Complexity: O(s.length()). Space: O(1).
AC Java:
题目:
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].
题解:
计数"("的数目. 遇到"("加一. 遇到")" 减一.
遇到"*". 可能分别对应"(", ")"和empty string 三种情况. 所以计数可能加一, 减一或者不变. 可以记录一个范围[lo, hi].
lo维持在0或以上的位置.
但若是hi都小于0, 说明确定的")"更多, 直接返回false.
否则看最后lo能否能停在0.
Time Complexity: O(s.length()). Space: O(1).
AC Java:
1 class Solution { 2 public boolean checkValidString(String s) { 3 if(s == null || s.length() == 0){ 4 return true; 5 } 6 7 int lo = 0; 8 int hi = 0; 9 for(int i = 0; i<s.length(); i++){ 10 if(s.charAt(i) == '('){ 11 lo++; 12 hi++; 13 }else if(s.charAt(i) == ')'){ 14 lo--; 15 hi--; 16 }else{ 17 lo--; 18 hi++; 19 } 20 21 if(hi < 0){ 22 return false; 23 } 24 lo = Math.max(lo, 0); 25 } 26 27 return lo == 0; 28 } 29 }
相关文章推荐
- [LeetCode] Valid Parenthesis String 验证括号字符串
- [LeetCode]Valid Parenthesis String
- LeetCode-Valid Parenthesis String
- leetcode 678 Valid Parenthesis String
- LeetCode - Valid Parenthesis
- LeetCode-20 valid parenthesis
- Leetcode 20 Valid Parenthesis
- leetcode 678. Valid Parenthesis String 有效括号的判断 + 保存index遍历
- [LeetCode] 678. Valid Parenthesis String 验证括号字符串
- [Leetcode] 678. Valid Parenthesis String 解题报告
- LeetCode678. Valid Parenthesis String
- String-678-Valid Parenthesis String
- Leetcode-20: Valid Parentheses
- leetcode 32. Longest Valid Parentheses
- Leetcode: Valid Palindrome
- leetcode--32. Longest Valid Parentheses
- leetcode-20-Valid Parentheses
- leetcode:20. Valid Parentheses
- LeetCode Valid Sudoku
- leetcode Graph Valid Tree