1. 程式人生 > >stack 處理 pop時丟擲異常

stack 處理 pop時丟擲異常

leetcode 20 :https://leetcode.com/problems/valid-parentheses/description/

如果 stack 為空時,pop()會 丟擲exception, 處理的方法如下:

try {
char top = st.pop();

if (! (
(top == '(' && s_i == ')') ||
(top == '{' && s_i == '}') || 
(top == '[' && s_i == ']') 
)
)
return false;

}

catch (Exception e) {
return false; } }