LeetCode刷题:20. Valid Parentheses
程序员文章站
2024-03-16 12:59:10
...
LeetCode刷题:20. Valid Parentheses
原题链接:https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
算法设计
package com.bean.algorithm.basic;
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s) {
if (s == "" || s.isEmpty())
return true;
Stack stack = new Stack();
for (int index = 0; index < s.length(); index++) {
char ch = s.charAt(index);
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
char expected;
if (ch == ')')
expected = '(';
else if (ch == ']')
expected = '[';
else
expected = '{';
if (stack.isEmpty()) {
return false;
}
char actual = (char) stack.pop();
if (actual != expected) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
ValidParentheses vp=new ValidParentheses();
//String input="()[]{}";
String input="([)]";
boolean flag=vp.isValid(input);
System.out.println("flag is: "+flag);
}
}
程序运行结果:
当 input = “()[]{}”时,返回 flag = true;
当 input = “([)]”时,返回 flag = false
上一篇: 查找两个有序数组合并后的中位数
推荐阅读
-
LeetCode刷题:260. Single Number III
-
LeetCode刷题:20. Valid Parentheses
-
LeetCode刷题:349. Intersection of Two Arrays&350. Intersection of Two Arrays II
-
【leetcode刷题日记】Task10-两数相加
-
LeetCode刷题笔记 892. 三维形体的表面积 【几何】
-
leetcode每日刷题之数组(四)27.移除元素(一个让你说卧槽的题解)
-
leetcode每日刷题之链表篇(二)奇偶链表,移除重复节点
-
LeetCode刷题: 【945】使数组唯一的最小增量
-
LeetCode刷题(0009)---7. 整数反转
-
LeetCode刷题(0010)---9. 回文数,python