尝试检查括号是否平衡或不平衡

huangapple 未分类评论44阅读模式
英文:

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 == &#39;[&#39; &amp;&amp; c == &#39;]&#39;)
			return true;
		if (this.type == &#39;{&#39; &amp;&amp; c == &#39;}&#39;)
			return true;
		if (this.type == &#39;(&#39; &amp;&amp; c == &#39;)&#39;)
			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&lt;Bracket&gt; opening_brackets_stack = new Stack&lt;Bracket&gt;();
		for (int position = 0; position &lt; text.length(); ++position) {
			char next = text.charAt(position);

			if (next == &#39;(&#39; || next == &#39;[&#39; || next == &#39;{&#39;) {
				// Process opening bracket, write your code here
				Bracket tmp = new Bracket(next, position);

				opening_brackets_stack.push(tmp);
				break;

			}

			if (next == &#39;)&#39; || next == &#39;]&#39; || next == &#39;}&#39;) {
				// 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 &amp;&amp; opening_brackets_stack.isEmpty()) {
			System.out.println(&quot;Success&quot;);
		} else {
			if (pos == 0) {
				while (opening_brackets_stack.size() &gt; 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&lt;Bracket&gt; opening_brackets_stack = new Stack();
        //traverse the string
        for(int position=0;position&lt;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==&#39;(&#39; || current==&#39;[&#39; || current==&#39;{&#39;) {
                
                Bracket pos = new Bracket(current,position);
              
                opening_brackets_stack.push(pos);
            }

            if(current==&#39;)&#39; || current==&#39;]&#39; || current==&#39;}&#39;) {
               
                Bracket newItem = opening_brackets_stack.pop();
                
                if(!newItem.Match(current)) {  
                    System.out.println(position+1);
                    return;
                }
            }

        }

        if(opening_brackets_stack.isEmpty()) {
            System.out.println(&quot;Success&quot;);
        }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&lt;Bracket&gt; opening_brackets_stack = new Stack&lt;Bracket&gt;();
    for (int position = 0; position &lt; text.length(); ++position) {
        char next = text.charAt(position);

        if (next == &#39;(&#39; || next == &#39;[&#39; || next == &#39;{&#39;) {
            // Process opening bracket, write your code here
            Bracket tmp = new Bracket(next, position);

            opening_brackets_stack.push(tmp);
            continue;  // continue not break

        }

        if (next == &#39;)&#39; || next == &#39;]&#39; || next == &#39;}&#39;) {
            // 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 &amp;&amp; opening_brackets_stack.isEmpty())
    System.out.println(&quot;Success&quot;);
 else
    System.out.println(&quot;Failure at position: &quot;+pos);
}
}

Better solution:

private static boolean checkParenthesisMap(String text) {
    Map&lt;Character, Character&gt; brackets = Map.of(&#39;{&#39;, &#39;}&#39;, &#39;(&#39;, &#39;)&#39;, &#39;[&#39;, &#39;]&#39;);
    Stack&lt;Character&gt; bracStack = new Stack&lt;&gt;();
    for (int i=0; i&lt;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&lt;Character&gt; brackets = new Stack&lt;&gt;();
    boolean equilibrateBrackets = true;
    string = getBrackets(string);

    for (int i = 0; i &lt; string.length(); i++) {
        // If string contains &#39;{&#39;, &#39;[&#39;, or &#39;(&#39; this will be added to the Stack named brackets
        if (string.charAt(i) == &#39;{&#39; || string.charAt(i) == &#39;[&#39; || string.charAt(i) == &#39;(&#39;) {
            brackets.push(string.charAt(i));
        // Else if Stack is Empty there&#180;s no reason to execute this part.
        } else if (!brackets.isEmpty()) {
            switch (string.charAt(i)) {
                case &#39;)&#39;:
                    if (brackets.peek() == &#39;(&#39;) brackets.pop();
                case &#39;]&#39;:
                    if (brackets.peek() == &#39;[&#39;) brackets.pop();
                case &#39;}&#39;:
                    if (brackets.peek() == &#39;{&#39;) brackets.pop();
            }
        // Else if Stack is empty and the next char is a &quot;closing brackets&quot; means that that the brackets are not properly placed
        } else if (brackets.isEmpty() &amp;&amp; string.charAt(i) == &#39;}&#39; || string.charAt(i) == &#39;]&#39; || string.charAt(i) == &#39;)&#39;) {
            equilibrateBrackets = false;
            break;
        }
    }

    return equilibrateBrackets;
}

huangapple
  • 本文由 发表于 2020年4月11日 11:25:39
  • 转载请务必保留本文链接:https://java.coder-hub.com/61151747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定