我正在为源代码中的测试平衡括号编写java代码。
以下是检查平衡括号的代码。 主要
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() != '[') {
System.out.println("yes");
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();
}
如果我只使用单行测试用例,那就好了。
input1 : abctex()[]
output: true
现在我遇到了问题,如何用最后一个索引检查每个句子中的平衡括号是点('。')。
例如 输入
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].
A rope may form )( a trail in a maze.
Help( I[m being held prisoner in a fortune cookie factory)].
([ (([( [ ] ) ( ) (( ))] )) ]).
.
.
输出:
true
true
false
false
false
true
true
答案 0 :(得分:2)
你的外部循环不应该是行而是句子。这是读到点的所有内容并将其用作process
的输入。重复直到结束。