【问题标题】:Delimiter Matching using Stack使用堆栈的分隔符匹配
【发布时间】:2016-06-19 06:14:13
【问题描述】:

这里有个小问题你可以考虑回答一下;

这里是代码;

public void analyze (String input, int length, int j){
    if (j == length){
        return;
    }
    if(input.charAt(j) == '{' || input.charAt(j) == '(')
        push(input.charAt(j));
    else
        pop();
    j++;    

    analyze (input, length, j);
}

输出:

Original List: {()}



List: {

好吧,问题是列表应该是空的,但我似乎找不到解决方案。

提前谢谢你。

以下是完整代码: http://pastebin.com/nXc79gHf

【问题讨论】:

  • 在第一次调用分析()之前,长度似乎设置为 input.length()-1。但我不确定,因为我需要更多代码才能理解。
  • 您在哪里寻找右大括号或圆括号?您认为这可能与您的问题有关吗?
  • @JimGarrison 我想如果它没有打开那么它就会弹出
  • 如果它既不是打开也不是关闭分隔符怎么办?此外,您还没有展示您如何处理分析结果,以及如何产生输出。没有它,我们都只是猜测。
  • @SergeyChechenev 当我添加时 - 如果(j == length - 1) 输出为List: {(,则为 1

标签: java data-structures linked-list stack


【解决方案1】:

假设您的输入仅包含 '}', '{''(', ')' 字符。

用下面的代码替换(假设push()pop() 可以正常工作)...

public void analyze(String input, int length, int j){
        if (j >= length) return;
        if(input.charAt(j) == '{' || input.charAt(j) == '(')
            push(input.charAt(j));
        else if(input.charAt(j) == '}' || input.charAt(j) == ')')
            pop();
        analyze (input, length, ++j);
    }

使用analyze(input, input.length(), 0);调用

例如。 {()}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    相关资源
    最近更新 更多