Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java中的HashMap进行括号配对?_Java - Fatal编程技术网

使用java中的HashMap进行括号配对?

使用java中的HashMap进行括号配对?,java,Java,我试图使用HashMap来匹配使用索引+1的括号对的顺序,但是我未能正确地在另一个括号中排列一个括号?如果我有这些作为输入: ()[[]] 那么我希望输出是 1 2 3 6 4 5 我试过用这条线 mapping.put(input.substring(0, i).lastIndexOf("[") + 1, i + 1) 但结果是 1 2 4 6 谁能帮我修一下密码吗?我是初学者,请不要对我太苛刻。谢谢大家! 我不太清楚你为什么想要一个HashMap。通常,这样的任

我试图使用HashMap来匹配使用索引+1的括号对的顺序,但是我未能正确地在另一个括号中排列一个括号?如果我有这些作为输入:

()[[]]

那么我希望输出是

1 2
3 6
4 5
我试过用这条线

mapping.put(input.substring(0, i).lastIndexOf("[") + 1, i + 1)
但结果是

1 2
4 6

谁能帮我修一下密码吗?我是初学者,请不要对我太苛刻。谢谢大家!

我不太清楚你为什么想要一个HashMap。通常,这样的任务是通过使用堆栈来完成的。您只需遍历字符串的所有字符。每次找到左括号(圆括号、大括号)时,都会将其(及其位置)放在堆栈上。每次找到结束括号(括号、大括号)时,检查堆栈顶部时,它应该包含相同类型的开始括号。如果不是,则表示字符串不平衡,如
([)]
。否则,您知道开始括号的位置(它也存储在堆栈上),可以将其与结束括号位置一起打印。

我认为您应该使用堆栈,这对您来说也更容易

如果您不知道堆栈是什么,我将向您解释:

堆栈使用后进先出原则,代表“后进先出”,意思是你放入堆栈的最后一件东西将是你从中得到的第一件东西。您可以执行诸如将项目推送到堆栈或弹出其中一个项目或仅检查堆栈上的内容之类的操作

所以,也许只要看看->读一下,你就会明白:)


我希望这对您有所帮助,如果不是这样,那么就告诉它,我会尽力帮助您:)

您可以使用堆栈来保持开始和结束括号的位置。因此,当您遇到一个开始括号时,将位置和括号放入堆栈中,对于每个“i”检查是否是结束括号,如果是,则只需弹出开始括号的位置并将其放入结果图中

e、 g

静态类对{
字符括号;
内部位置;
公共对(字符括号,int位置){
这个括号=括号;
这个位置=位置;
}
}
公共静态void main(字符串[]args)引发异常{
字符串方括号序列=“()[[]”;
堆栈=新堆栈();
Map charMap=Map.of(
')', '(',
'}', '{',
']', '['
);
Map mapping=newhashmap();
对于(int i=0;i 0)
抛出新异常(“格式错误的括号序列”);
for(Map.Entry:mapping.entrySet()){
System.out.println(entry.getKey()+“”+entry.getValue());
}
}
试试看:

public class ParenthesisDemo {

    public static void main(String[] args) throws Exception {
        String expression = "(5x7)[[]{}]";

        System.out.println("Input expression : " + expression);
        Map<Integer, Integer> parenthesisSequence = getParenthesisSequence(expression);
        for (Map.Entry<Integer, Integer> entry : parenthesisSequence.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }

    public static Map<Integer, Integer> getParenthesisSequence(String expression) throws Exception {
        Stack<Parenthesis> stack = new Stack<>();
        Map<Character, Character> parenthesisPair = new HashMap<Character, Character>();
        parenthesisPair.put(')', '(');
        parenthesisPair.put('}', '{');
        parenthesisPair.put(']', '[');

        Character parenthesis[] = { '{', '}', '[', ']', '(', ')' };
        Set<Character> validParenthesisSet = new HashSet<>(Arrays.asList(parenthesis));

        Map<Integer, Integer> parenthesisSequenceMap = new HashMap<>();

        for (int k = 0; k < expression.length(); k++) {
            char openParenthesis = expression.charAt(k);

            if (validParenthesisSet.contains(openParenthesis)) {

                if (parenthesisPair.containsKey(openParenthesis)) {
                    char closeParenthesis = parenthesisPair.get(openParenthesis);

                    if (stack.size() == 0
                            || stack.peek().type != closeParenthesis) {
                        throw new Exception("Invalid Expression");
                    }

                    int startIndex = stack.pop().index;
                    parenthesisSequenceMap.put(startIndex + 1, k + 1);
                } else {
                    stack.push(new Parenthesis(openParenthesis, k));
                }
            }
        }

        if (stack.size() > 0)
            throw new Exception("Invalid Expression");

        return parenthesisSequenceMap;
    }
}

class Parenthesis {
    char type;
    int index;

    public Parenthesis(char type, int index) {
        this.type = type;
        this.index = index;
    }
}

你能展示一个,而不是仅仅一行代码吗?这正是我在我现在删除的注释中试图得到的:)-我只是忘记了潜在的不平衡输入,这是一个很好的发现。嘿!我实际上是按照你说的方式使用堆栈,但我不知道如何使用堆栈来识别原始str中括号的索引ing.有专门的方法吗?谢谢!你应该把找到的括号的索引也放在堆栈上。例如,你可以创建一个助手类,它只有两个字段-一个字符和一个整数。你将创建一个此类对象的堆栈。然后当你找到一个开始符号时,你在堆栈上放上一个新的thi实例s类,并使用找到的开始符号和字符串中的当前位置对其进行初始化。当找到结束符号时,从堆栈中弹出()对象,并从其整数字段中获取开始括号的位置。也许可以看看java实现
public class ParenthesisDemo {

    public static void main(String[] args) throws Exception {
        String expression = "(5x7)[[]{}]";

        System.out.println("Input expression : " + expression);
        Map<Integer, Integer> parenthesisSequence = getParenthesisSequence(expression);
        for (Map.Entry<Integer, Integer> entry : parenthesisSequence.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }

    public static Map<Integer, Integer> getParenthesisSequence(String expression) throws Exception {
        Stack<Parenthesis> stack = new Stack<>();
        Map<Character, Character> parenthesisPair = new HashMap<Character, Character>();
        parenthesisPair.put(')', '(');
        parenthesisPair.put('}', '{');
        parenthesisPair.put(']', '[');

        Character parenthesis[] = { '{', '}', '[', ']', '(', ')' };
        Set<Character> validParenthesisSet = new HashSet<>(Arrays.asList(parenthesis));

        Map<Integer, Integer> parenthesisSequenceMap = new HashMap<>();

        for (int k = 0; k < expression.length(); k++) {
            char openParenthesis = expression.charAt(k);

            if (validParenthesisSet.contains(openParenthesis)) {

                if (parenthesisPair.containsKey(openParenthesis)) {
                    char closeParenthesis = parenthesisPair.get(openParenthesis);

                    if (stack.size() == 0
                            || stack.peek().type != closeParenthesis) {
                        throw new Exception("Invalid Expression");
                    }

                    int startIndex = stack.pop().index;
                    parenthesisSequenceMap.put(startIndex + 1, k + 1);
                } else {
                    stack.push(new Parenthesis(openParenthesis, k));
                }
            }
        }

        if (stack.size() > 0)
            throw new Exception("Invalid Expression");

        return parenthesisSequenceMap;
    }
}

class Parenthesis {
    char type;
    int index;

    public Parenthesis(char type, int index) {
        this.type = type;
        this.index = index;
    }
}
Input expression : ({}[])[[]{}]
Output : 
1 6
2 3
4 5
7 12
8 9
10 11