请为我解释代码的这些部分

问题描述

我需要检查输入字符串中的平衡表达式。 通过阅读找到代码的指南和一些youtube视频,可以了解大多数Java代码的工作方式。 但其中的某些部分仍然无法理解,我在这些部分中添加了注释。

package homework;
import java.util.Stack;
import java.util.Scanner;
public class homewokr2 {

    public static void main(String[] args) {
        Scanner myScan = new Scanner(system.in);
         System.out.println("enter code for which to check if expression is balanced ");
        
        String code = myScan.next();
    
         String checkBalancedExpr1=checkBalancedParentesis("" +code);
         System.out.println(""+checkBalancedExpr1);
    
         myScan.close();
 }
 public static String checkBalancedParentesis(String expr)
 {
 if (expr.isEmpty())    *// why is it (expr) should it not be (stack.isEmpty)?*
 return "Balanced";
 Stack<Character> stack = new Stack<Character>();
 for (int i = 0; i < expr.length(); i++)
 {
 char current = expr.charat(i);
 if (current == '{' || current == '(' || current == '[')
 {
 stack.push(current);
 }
 if (current == '}' || current == ')' || current == ']')
 {
 if (stack.isEmpty())
 return "Not Balanced";
 char last = stack.peek();
 if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
 stack.pop();
 else 
 return "Not Balanced";
 }
 }
 return stack.isEmpty()?"Balanced":"Not Balanced"; // i dont rly get this part of it
 }
}

解决方法

if (expr.isEmpty()) *// why is it (expr) should it not be (stack.isEmpty)?* return "Balanced";

这只是检查边缘条件:如果使用完全空的字符串调用此方法,则显然很平衡。这就是所有的事情。

它也是完全不必要的:如果删除该代码,它仍然可以正常工作:毕竟,这里有0个表达式,因此main for循环(循环输入字符串中的每个字符)将循环0次(嘿,空字符串,没有字符,所以没有循环),因此堆栈显然是空的,它返回“平衡”。

return stack.isEmpty()?"Balanced":"Not Balanced"; // i dont rly get this part of it

如果堆栈对象(表示...一个堆栈,因此为名称)为空,则表示它是平衡的。如果经过每个角色之后仍然有东西在那儿,那就不是了。这里是一个简单的例子:

输入(hello(),然后...

for循环运行8次;每个字符一次。第一次运行时,它会看到第一个(并将其放在堆栈中。第二次运行时,它将看到第二个(并将其放在堆栈中;现在堆栈为['(','(']。接下来的5次运行将看到“ h”,“ e”,“ l”,“ l”和“ o”,它们都被完全忽略并且没有任何作用。第8次运行时,它会看到“)”,其匹配值等于当前堆栈顶部的结束符(堆栈顶部= stack.peek()),因此弹出堆栈:顶部是删除,现在堆栈又回到了['(']

现在,当我们用完字符时,循环结束。鉴于堆栈不是空的,它是不平衡的,并且将返回该堆栈。