LeetCode Top 100 Liked Questions 20. Valid Parentheses (Java版; Easy)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


​welcome to my blog​

LeetCode Top 100 Liked Questions 20. Valid Parentheses (Java版; Easy)

题目描述

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
class Solution {
public boolean isValid(String s) {
int n = s.length();
if(n==0){
return true;
}
Stack<Character> stack = new Stack<>();
stack.push('*');
for(int i=0; i<n; i++){
char ch = s.charAt(i);
if(ch=='(' || ch=='[' ||ch=='{'){
stack.push(ch);
}else if(ch==')'){
char ch2 = stack.pop();
if(ch2!='('){
return false;
}
}else if(ch==']'){
char ch2 = stack.pop();
if(ch2!='['){
return false;
}
}else if(ch=='}'){
char ch2 = stack.pop();
if(ch2!='{'){
return false;
}
}
}
return stack.size()==1;
}
}

第一次做, 核心思想:使用一个栈, 只压入括号的左半边, 当遇到括号的右半边时, 如果此括号的右半边和栈顶元素配对, 则弹出栈顶元素, 继续下一轮循环; 如果此括号的右半边和栈顶元素不配对, 则直接返回false; 循环结束后,如果栈中没有元素则返回true, 如果栈中有元素则返回false

  • 自己想到了用栈解决这个问题, 值得鼓励, 虽然是easy级别
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
if(s==null || s.length()%2==1)
return false; //和面试官商量
if(s.length()==0)
return true;

//栈中只压括号的左半边
Stack<Character> stack = new Stack<>();
char curr;
for(int i=0; i<s.length(); i++){
curr = s.charAt(i);
if(curr=='(' || curr=='[' || curr=='{')
stack.push(curr);
else if(!stack.isEmpty() && isMatch(stack.peek(), curr))
stack.pop();
else//curr==')' ']' '}'但是stack为空或者curr!=stack.peek()
return false;
}
return stack.isEmpty();
}
public boolean isMatch(char a, char b){
if(a=='(')
return b==')';
if(a=='[')
return b==']';
if(a=='{')
return b=='}';
return false;
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java