Java平衡表达式用多行检查{[()]}

时间:2018-03-15 11:45:04

标签: java

我有一些小代码来检查余额表达式{[()]}。

我使用的main

String s = reader.nextLine();
System.Out.println (process(s));

代码:

public static boolean process(String s) {
    Stack<Character> stack  = new Stack<Character>();
    for(int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if(c == '[' || c == '(' || c == '{' ) {     
            stack.push(c);
        } else if(c == ']') {
            if(stack.isEmpty() || stack.pop() != '[') {
                return false;
            }
        } else if(c == ')') {
            if(stack.isEmpty() || stack.pop() != '(') {
                return false;
            }           
        } else if(c == '}') {
            if(stack.isEmpty() || stack.pop() != '{') {
                return false;
            }
        }   
    }
    return stack.isEmpty();
}

如果

,那没关系
Input : Hello (the [first] I will see in (heaven) is a score list).
Output : True

但是,如果我输入多个不起作用

Input : So when I die (the [first] I will see in (heaven) is a score list).

[ first in ] ( first out ).
Half Moon tonight (At least it is better than no Moon at all].

Output : True

实际输出必须是:

True
True 
False

我不知道为什么?请帮帮我。

1 个答案:

答案 0 :(得分:0)

鉴于您使用的是reader.nextLine(),我认为您的readerjava.util.Scanner

您只传递第一行,因此请遍历输入的所有行,并忽略空行:

Scanner reader = new Scanner(System.in);
while(reader.hasNext()) {
  String s = reader.nextLine();
  if(s.trim().length() > 0) {
    System.out.println (process(s));
  }
}

这应该调用process 3次,使用以下字符串:

  • So when I die (the [first] I will see in (heaven) is a score list).
  • [ first in ] ( first out ).
  • Half Moon tonight (At least it is better than no Moon at all].