> 文档中心 > 判断字符串中的括号是否有效(合法)

判断字符串中的括号是否有效(合法)

给定一个字符串,其中只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效
例如:

"()"  有效"()[]{}"有效"(]"   无效"([)]"无效"{[]}"有效

思路:考虑使用栈来操作
直接上代码

public boolean isValid(String s) {// LinkedList可以很好的作为一个栈来使用 LinkedList list = new LinkedList(); for (char c : s.toCharArray()) {     if (c == '(' || c == '[' || c == '{') {  list.add((int) c);  continue;     }     if (c == ')') {  if (list.size() == 0 || list.getLast() != '(') return false;  list.removeLast();  continue;     }     if (c == ']') {  if (list.size() == 0 || list.getLast() != '[') return false;  list.removeLast();  continue;     }     if (c == '}') {  if (list.size() == 0 || list.getLast() != '{') return false;  list.removeLast();  continue;     } } return list.isEmpty();}

参考链接:https://blog.csdn.net/hixiaoxiaoniao/article/details/109727727

开发者涨薪指南 判断字符串中的括号是否有效(合法) 48位大咖的思考法则、工作方式、逻辑体系素彩网