有效的括号

This commit is contained in:
LingZhaoHui 2021-02-06 22:48:03 +08:00
parent 308c9ec6cc
commit 69dd97c054
2 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,25 @@
package com.leetcode.num;
/**
* 给你一个由 '1'陆地 '0'组成的的二维网格请你计算网格中岛屿的数量
岛屿总是被水包围并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成
此外你可以假设该网格的四条边均被水包围
来源力扣LeetCode
链接https://leetcode-cn.com/problems/number-of-islands
*/
public class NumIslands {
public int numIslands(char[][] grid) {
return 0;
}
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,56 @@
package com.leetcode.string;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* 给定一个只包括 '('')''{''}''['']' 的字符串 s 判断字符串是否有效
有效字符串需满足
左括号必须用相同类型的右括号闭合
左括号必须以正确的顺序闭合
来源力扣LeetCode
链接https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有商业转载请联系官方授权非商业转载请注明出处
*/
public class IsValidKuoHao {
private static Map<Character, Character> kuohao = new HashMap<Character, Character>() {{
put('(', ')');
put('{', '}');
put('[', ']');
}};
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (stack.empty()) {
stack.push(c);
continue;
}
Character pre = stack.peek();
if (pre == null || kuohao.get(pre) == null) {
stack.push(c);
continue;
}
if (kuohao.get(pre) == c) {
stack.pop();
} else {
stack.push(c);
}
}
return stack.empty();
}
public static void main(String[] args) {
IsValidKuoHao validKuoHao = new IsValidKuoHao();
String str = "{[]}";
boolean isValid = validKuoHao.isValid(str);
System.out.println(isValid);
}
}