9

#yyds干货盘点# LeetCode 热题 HOT 100: 有效的括号

 2 years ago
source link: https://blog.51cto.com/u_13321676/5689292
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 热题 HOT 100: 有效的括号

精选 原创

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

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

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

有效字符串需满足:

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

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

每个右括号都有一个对应的相同类型的左括号。

输入:s = "()"

输出:true

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

输出:true

输入:s = "(]"

输出:false

代码实现:

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