Q678 有效的括号字符串

给定一个只包含三种字符的字符串:*,写一个函数来检验这个字符串是否为有效字符串。有效字符串具有如下规则:

  1. 任何左括号 ( 必须有相应的右括号 )
  2. 任何右括号 ) 必须有相应的左括号 (
  3. 左括号 ( 必须在对应的右括号之前 )
  4. * 可以被视为单个右括号 ) ,或单个左括号 ( ,或一个空字符串。
  5. 一个空字符串也被视为有效字符串。

示例 1:

输入: "()"
输出: True

示例 2:

输入: "(*)"
输出: True

示例 3:

输入: "(*))"
输出: True

注意:

  1. 字符串大小将在 [1,100] 范围内。
public boolean checkValidString(String s) {
        if (s == null || s.length() == 0)
            return true;

        char[] chs = s.toCharArray();
        char[] chsReverse = s.toCharArray();
        for (int i = 0; i < chsReverse.length / 2; i++) {
            char c = chsReverse[i];
            if (chsReverse[chsReverse.length - 1 - i] == '*')
                chsReverse[i] = '*';
            else
                chsReverse[i] = (chsReverse[chsReverse.length - 1 - i] == ')' ? '(' : ')');

            if (c == '*')
                chsReverse[chsReverse.length - 1 - i] = '*';
            else
                chsReverse[chsReverse.length - 1 - i] = (c == ')' ? '(' : ')');
        }

        return check(chs) && check(chsReverse);
    }


    private boolean check(char[] s) {

        int left = 0;
        int right = 0;
        int nil = 0;

        for (char c : s) {
            if (c == '*')
                nil++;
            else if (c == '(')
                left++;
            else if (c == ')')
                right++;

            if (right - left > nil )
                return false;
        }

        if (left + nil < right || right + nil < left)
            return false;

        return true;
    }

猜你喜欢

转载自www.cnblogs.com/WeichengDDD/p/10739220.html
今日推荐