Leetcode――678. Valid Parenthesis String(匹配括号)

匿名 (未验证) 提交于 2019-12-03 00:22:01

https://leetcode.com/problems/valid-parenthesis-string/description/

给定一个字符串,字符串中可以有(、)、*左括号,有括号和星号,星号可以表示左括号或右括号或空字符。返回该字符串是否可以左右括号完全匹配。

示例一: 递归

class Solution {     public boolean checkValidString(String s) {         if(s == null) return true;         return isValid(s, 0, 0);     }      private boolean isValid(String s, int index, int count) {         if(count < 0)             return false;         for(int i = index; i < s.length(); i++) {             if(s.charAt(i) == '(')                 count ++;             else if(s.charAt(i) == ')')                 if(count <= 0) return false;                 else count--;             else if(s.charAt(i) == '*')                  return isValid(s, i + 1, count + 1) || isValid(s, i + 1, count) || isValid(s, i + 1, count -1);         }         return count == 0;             } }

示例二:这个方法真的太神奇了

class Solution {             public boolean checkValidString(String s) {                  int l = 0;               int r = 0;         for(char c: s.toCharArray()) {             l = c == '(' ? 1: -1;             r = c == ')' ? -1 : 1;             if(r < 0) return false;             l = Math.max(l, 0);         }         return lo == 0;     } }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!