【Java】leetcode题解-有效括号利用栈LIFO实现

admin 2022年1月10日03:30:51评论29 views字数 641阅读2分8秒阅读模式

我的个人博客

孤桜懶契:http://gylq.github.io

Leetcode题目 20

image-20210625172525394

执行结果

image-20210625172657711

Solution题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public boolean isValid(String s){

Stack<Character> stack = new Stack<>();
for(int i = 0 ; i < s.length(); i ++){
char c = s.charAt(i);
if(c == '(' || c == '[' || c== '{')
stack.push(c);
else {
if(stack.isEmpty())
return false;

char topChar = stack.pop();
if(c == ')' && topChar != '(')
return false;
if(c == ']' && topChar != '[')
return false;
if(c == '}' && topChar != '{')
return false;

}
}
return stack.isEmpty();
}

public static void main(String[] args){

System.out.println((new Solution()).isValid("()[]{}"));
System.out.println((new Solution()).isValid("(])]{}"));
}
}

FROM:gylq.gitee Author:孤桜懶契

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年1月10日03:30:51
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【Java】leetcode题解-有效括号利用栈LIFO实现https://cn-sec.com/archives/729939.html

发表评论

匿名网友 填写信息