0
点赞
收藏
分享

微信扫一扫

[算法]括号字符串是否合法


括号字符串是否合法

(,判断其中的括号是否匹配正确,比如(()())正确,((())()错误,不允许使用栈

这种类似题的常见思路是栈,对于左括号入栈,如果遇到右括号,判断此时栈顶是不是左括号,是则将其出栈,不是则该括号序列不合法。

int count字段。

public       static       boolean checkBrackets(String       str) {     

char[] cs =       str.toCharArray();     

int       count =       0;     

for (      int i =       0; i < cs.length; i++) {     

if (cs[i] ==       '(')     

count++;     

else

count--;     

if (      count <       0) {     

return       false;     

      			}     

      		}     

      	}     



return       count ==       0;     

      }

举报

相关推荐

0 条评论