有效的括号
This commit is contained in:
parent
308c9ec6cc
commit
69dd97c054
|
@ -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) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
|
@ -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);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue