【leetcode系列】Valid Parentheses
2024-10-29 17:40:01 211人阅读
非常经典的问题,使用栈来解决,我这里自己实现了一个栈,当然也能够直接用java自带的Stack类。
自己实现的栈代码:
import java.util.LinkedList;
class StackOne {
LinkedList<Object> data;
int top;
int maxSize;
StackOne(int size) {
// TODO Auto-generated constructor stub
top = -1;
maxSize = 100;
data = http://www.mamicode.com/new LinkedList();> 推断输出是否有效:
public class Solution {
public static boolean isValid(String in) {
StackOne stackOne = new StackOne(100);
boolean result = false;
char[] inArray = in.toCharArray();
for (char i : inArray) {
if (i == '(' || i == '[' || i == '{') {
try {
stackOne.push(i);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
continue;
}
if (i == ')') {
if (stackOne.isEmpty()) {
result = false;
} else {
char tmp = '\u0000';
try {
tmp = (Character) stackOne.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tmp == '(') {
result = true;
}
}
}
if (i == ']') {
if (stackOne.isEmpty()) {
result = false;
} else {
char tmp = '\u0000';
try {
tmp = (Character) stackOne.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tmp == '[') {
result = true;
}
}
}
if (i == '}') {
if (stackOne.isEmpty()) {
result = false;
} else {
char tmp = '\u0000';
try {
tmp = (Character) stackOne.pop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (tmp == '{') {
result = true;
}
}
}
}
if (!stackOne.isEmpty()) {
result = false;
}
return result;
}
public static void main(String[] args) {
System.out.print(isValid("(}"));
}
}
【leetcode系列】Valid Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉:
投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。
×
https://www.u72.net/daima/nvc27.html