【问题标题】:Why isn't this return statement doing anything?为什么这个 return 语句没有做任何事情?
【发布时间】:2021-05-06 06:30:51
【问题描述】:

我有这段代码,它检查像“{{}[]}”这样的字符串中的括号是否处于有效顺序:

import java.util.*;
public class BraceChecker {
  private static HashMap<String,String> dict=new HashMap<>(){{
    put(")","(");
    put("]","[");
    put("}","{");
  }};
  public boolean isValid(String braces) {
    Stack<String> stack=new Stack<>();
    for(String s:braces.split("")){
      if(dict.get(s)==null){
        stack.push(s);
        System.out.println("test");
      }
      else
        try{
          if(!stack.pop().equals(dict.get(s))){
            System.out.println("what");
            return false;
          }
        }catch(EmptyStackException e){return false;}
    }
    return true;
  }
}

对于字符串中的每个字符,如果是左括号,则将其添加到堆栈中,如果是右括号,则删除一项。如果删除的项目与输入字符串中的括号不匹配,它应该返回 false。

但是当程序在应该返回false的字符串“[(])”上运行时,它返回true。 System.out.printlns 产生这个:

test
test
what
test
what
test
what
test
test
test
test
test
test
test

但是为什么程序到达第一个'what'时不返回false?我怎样才能让它返回 false?

【问题讨论】:

    标签: java return control-flow


    【解决方案1】:
        class Solution {
    
      // Hash table that takes care of the mappings.
      private HashMap<Character, Character> mappings;
    
      // Initialize hash map with mappings. This simply makes the code easier to read.
      public Solution() {
        this.mappings = new HashMap<Character, Character>();
        this.mappings.put(')', '(');
        this.mappings.put('}', '{');
        this.mappings.put(']', '[');
      }
    
      public boolean isValid(String s) {
    
        // Initialize a stack to be used in the algorithm.
        Stack<Character> stack = new Stack<Character>();
    
        for (int i = 0; i < s.length(); i++) {
          char c = s.charAt(i);
    
          // If the current character is a closing bracket.
          if (this.mappings.containsKey(c)) {
    
            // Get the top element of the stack. If the stack is empty, set a dummy value of '#'
            char topElement = stack.empty() ? '#' : stack.pop();
    
            // If the mapping for this bracket doesn't match the stack's top element, return false.
            if (topElement != this.mappings.get(c)) {
              return false;
            }
          } else {
            // If it was an opening bracket, push to the stack.
            stack.push(c);
          }
        }
    
        // If the stack still contains elements, then it is an invalid expression.
        return stack.isEmpty();
      }
    }
    

    这段代码绝对有效。我无法调试您的代码,但这是一个可运行的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-28
      • 2021-08-11
      • 2021-12-20
      • 2011-07-25
      • 2015-06-30
      • 2016-01-24
      • 2023-04-06
      • 2013-09-29
      相关资源
      最近更新 更多