英文:
Trying to check if brackets is balanced or unbalanced
问题
public class check_brackets {
public static void main(String[] args) throws IOException {
InputStreamReader input_stream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input_stream);
String text = reader.readLine();
Stack<Bracket> opening_brackets_stack = new Stack();
//traverse the string
for(int position=0;position<text.length();position++) {
//Get current char
char current = text.charAt(position);
//if the current char is starting bracker,then push it to stack
if(current=='(' || current=='[' || current=='{') {
Bracket pos = new Bracket(current,position);
opening_brackets_stack.push(pos);
}
if(current==')' || current==']' || current=='}') {
Bracket newItem = opening_brackets_stack.pop();
if(!newItem.Match(current)) {
System.out.println(position+1);
return;
}
}
}
if(opening_brackets_stack.isEmpty()) {
System.out.println("Success");
}else {
Bracket item = opening_brackets_stack.pop();
System.out.println(item.position+1);
}
}
}
英文:
Hi there I am working on assignment 1-1 and I'm having a hard time with this assignment When I submit the code below in the assignment with the input = [] it returns output = 0 when it should be returning output = Success. Any idea what I am doing wrong.
The below program should check if the string has balanced brackets
or not and should return the result.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Stack;
class Bracket {
Bracket(char type, int position) {
this.type = type;
this.position = position;
}
boolean Match(char c) {
if (this.type == '[' && c == ']')
return true;
if (this.type == '{' && c == '}')
return true;
if (this.type == '(' && c == ')')
return true;
return false;
}
char type;
int position;
}
class check_brackets {
public static void main(String[] args) throws IOException {
InputStreamReader input_stream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input_stream);
String text = reader.readLine();
int pos = 0;
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position) {
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{') {
// Process opening bracket, write your code here
Bracket tmp = new Bracket(next, position);
opening_brackets_stack.push(tmp);
break;
}
if (next == ')' || next == ']' || next == '}') {
// Process closing bracket, write your code here
Bracket item = opening_brackets_stack.pop();
if (!item.Match(next)) {
pos = position + 1;
break;
}
}
}
// Printing answer, write your code here
if (pos == 0 && opening_brackets_stack.isEmpty()) {
System.out.println("Success");
} else {
if (pos == 0) {
while (opening_brackets_stack.size() > 1)
opening_brackets_stack.pop();
pos = opening_brackets_stack.peek().position;
}
System.out.println(pos);
}
}
}
UPDATED CODE:
public class check_brackets {
public static void main(String[] args) throws IOException {
InputStreamReader input_stream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input_stream);
String text = reader.readLine();
Stack<Bracket> opening_brackets_stack = new Stack();
//traverse the string
for(int position=0;position<text.length();position++) {
//Get current char
char current = text.charAt(position);
//if the current char is starting bracker,then push it to stack
if(current=='(' || current=='[' || current=='{') {
Bracket pos = new Bracket(current,position);
opening_brackets_stack.push(pos);
}
if(current==')' || current==']' || current=='}') {
Bracket newItem = opening_brackets_stack.pop();
if(!newItem.Match(current)) {
System.out.println(position+1);
return;
}
}
}
if(opening_brackets_stack.isEmpty()) {
System.out.println("Success");
}else {
Bracket item = opening_brackets_stack.pop();
System.out.println(item.position+1);
}
}
}
答案1
得分: 0
以下是您提供的代码翻译后的内容:
你在每个位置都中断了循环,而你实际上需要继续。同时,将最终检查放在循环外部,
public class check_brackets { public static void main(String[] args) throws IOException {
InputStreamReader input_stream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input_stream);
String text = reader.readLine();
int pos = 0;
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position) {
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{') {
// 处理开括号,在这里写入您的代码
Bracket tmp = new Bracket(next, position);
opening_brackets_stack.push(tmp);
continue; // 使用 continue 而不是 break
}
if (next == ')' || next == ']' || next == '}') {
// 处理闭括号,在这里写入您的代码
if (opening_brackets_stack.isEmpty()) { // 检查栈是否为空的条件
pos = position + 1;
break;
}
// 处理闭括号,在这里写入您的代码
Bracket item = opening_brackets_stack.pop();
if (!item.Match(next)) {
pos = position + 1;
break;
}
}
}
// 打印答案,在这里写入您的代码
if (pos == 0 && opening_brackets_stack.isEmpty())
System.out.println("Success");
else
System.out.println("Failure at position: "+pos);
}
}
更好的解决方案:
private static boolean checkParenthesisMap(String text) {
Map<Character, Character> brackets = Map.of('{', '}', '(', ')', '[', ']');
Stack<Character> bracStack = new Stack<>();
for (int i=0; i<text.length(); i++){
char c = text.charAt(i);
if (brackets.containsKey(c))
bracStack.push(brackets.get(c));
else if (bracStack.isEmpty() || bracStack.pop() != c)
return false;
}
return bracStack.isEmpty();
}
注意:由于您要求只返回翻译好的部分,我已经省略了其他内容。如果您需要进一步的解释或指导,请随时提问。
英文:
You are breaking the loop at each position instead you need to continue. Also put final check outside for loop,
public class check_brackets { public static void main(String[] args) throws IOException {
InputStreamReader input_stream = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input_stream);
String text = reader.readLine();
int pos = 0;
Stack<Bracket> opening_brackets_stack = new Stack<Bracket>();
for (int position = 0; position < text.length(); ++position) {
char next = text.charAt(position);
if (next == '(' || next == '[' || next == '{') {
// Process opening bracket, write your code here
Bracket tmp = new Bracket(next, position);
opening_brackets_stack.push(tmp);
continue; // continue not break
}
if (next == ')' || next == ']' || next == '}') {
// Process closing bracket, write your code here
if (opening_brackets_stack.isEmpty()) { //condition the check if stack is empty
pos = position + 1;
break;
}
// Process closing bracket, write your code here
Bracket item = opening_brackets_stack.pop();
if (!item.Match(next)) {
pos = position + 1;
break;
}
}
}
// Printing answer, write your code here
if (pos == 0 && opening_brackets_stack.isEmpty())
System.out.println("Success");
else
System.out.println("Failure at position: "+pos);
}
}
Better solution:
private static boolean checkParenthesisMap(String text) {
Map<Character, Character> brackets = Map.of('{', '}', '(', ')', '[', ']');
Stack<Character> bracStack = new Stack<>();
for (int i=0; i<text.length(); i++){
char c = text.charAt(i);
if (brackets.containsKey(c))
bracStack.push(brackets.get(c));
else if (bracStack.isEmpty() || bracStack.pop() != c)
return false;
}
return bracStack.isEmpty();
}
答案2
得分: 0
static boolean checkEquilibrate(String string) {
Stack<Character> brackets = new Stack<>();
boolean equilibrateBrackets = true;
string = getBrackets(string);
for (int i = 0; i < string.length(); i++) {
// If string contains '{', '[', or '(' this will be added to the Stack named brackets
if (string.charAt(i) == '{' || string.charAt(i) == '[' || string.charAt(i) == '(') {
brackets.push(string.charAt(i));
// Else if Stack is Empty there's no reason to execute this part.
} else if (!brackets.isEmpty()) {
switch (string.charAt(i)) {
case ')':
if (brackets.peek() == '(') brackets.pop();
case ']':
if (brackets.peek() == '[') brackets.pop();
case '}':
if (brackets.peek() == '{') brackets.pop();
}
// Else if Stack is empty and the next char is a "closing brackets" means that the brackets are not properly placed
} else if (brackets.isEmpty() && (string.charAt(i) == '}' || string.charAt(i) == ']' || string.charAt(i) == ')')) {
equilibrateBrackets = false;
break;
}
}
return equilibrateBrackets;
}
英文:
You can try this too
static boolean checkEquilibrate(String string) {
Stack<Character> brackets = new Stack<>();
boolean equilibrateBrackets = true;
string = getBrackets(string);
for (int i = 0; i < string.length(); i++) {
// If string contains '{', '[', or '(' this will be added to the Stack named brackets
if (string.charAt(i) == '{' || string.charAt(i) == '[' || string.charAt(i) == '(') {
brackets.push(string.charAt(i));
// Else if Stack is Empty there´s no reason to execute this part.
} else if (!brackets.isEmpty()) {
switch (string.charAt(i)) {
case ')':
if (brackets.peek() == '(') brackets.pop();
case ']':
if (brackets.peek() == '[') brackets.pop();
case '}':
if (brackets.peek() == '{') brackets.pop();
}
// Else if Stack is empty and the next char is a "closing brackets" means that that the brackets are not properly placed
} else if (brackets.isEmpty() && string.charAt(i) == '}' || string.charAt(i) == ']' || string.charAt(i) == ')') {
equilibrateBrackets = false;
break;
}
}
return equilibrateBrackets;
}
专注分享java语言的经验与见解,让所有开发者获益!
评论