簡體   English   中英

嘗試檢查括號是平衡的還是不平衡的

[英]Trying to check if brackets is balanced or unbalanced

嗨,我正在處理作業 1-1,但我很難完成這個作業當我在作業中提交下面的代碼時,輸入 = [] 它返回 output = 0 當它應該返回 output = 成功時。 知道我做錯了什么。

下面的程序應該檢查字符串是否有balanced brackets並返回結果。

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);
        }
    }
}

更新代碼:

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);
        }

    }


}

您正在打破每個 position 的循環,而不是您需要繼續。 還要在 for 循環之外進行最終檢查,

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);
}
}

更好的解決方案:

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();
}

你也可以試試這個

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM