7

#yyds干货盘点# leetcode算法题:有效的括号

 2 years ago
source link: https://blog.51cto.com/u_13321676/5359529
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# leetcode算法题:有效的括号

原创

灰太狼_cxh 2022-06-06 10:09:19 博主文章分类:leetcode ©著作权

文章标签 字符串 i++ 代码实现 文章分类 Java 编程语言 阅读数188

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。

左括号必须以正确的顺序闭合。

输入:s = "()"

输出:true

输入:s = "()[]{}"

输出:true

输入:s = "(]"

输出:false

输入:s = "([)]"

输出:false

输入:s = "{[]}"

输出:true

代码实现:

class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}

Map<Character, Character> pairs = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK