题目:
https://leetcode-cn.com/problems/valid-parentheses/
题解:
https://blog.csdn.net/qq_42124842/article/details/91420306?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522162771045816780366553827%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=162771045816780366553827&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-4-91420306.first_rank_v2_pc_rank_v29&utm_term=java%E4%B8%AD%E6%A0%88&spm=1018.2226.3001.4187
思路:
?? ?类似的这种匹配问题,用栈来解决是比较方便的,因为栈本身是先进后出的规则,在匹配方面,根据从字符串中取到的数据, ?? ?与从栈中弹出(pop)的数据进行比较,判断是否配对,以及,是否满足配对规则。 ?? ? ?? ?就本题而言,大致步骤和思想如下: ?? ??? ?1,先行剔除字符个数不是偶数的字符串 ?? ??? ?2,创建Chracter类型的 Stack 对象 ?? ??? ?3,进行对字符串中所有字符的遍历配对 ?? ??? ??? ??? ?a, 从字符串中取出字符,判断字符类型(左侧 or 右侧)后,入栈 ?? ??? ??? ??? ?b, 针对右侧符号是否首先出来进行剔除判断 ?? ??? ??? ??? ?c, 将栈中字符pop,与字符串中数据进行比较 ?? ??? ?4, 判断栈是否为空
代码:
package Leetcode;
import java.util.Stack;
public class Leetcode020 {
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 top=stack.pop();
if (c == ']' && top!='[') {
return false;
}
if (c == ')' && top!='(') {
return false;
}
if (c == '}' && top!='{') {
return false;
}
}
}
return stack.isEmpty();
}
}
|