您的位置:首页 > 其它

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
'('
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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: