题目是:
Given a string, which contains ‘(’ and ‘)’ and some other characters, verify if it is a valid parentheses. It will not contains ‘{’ or ‘[’.
我的代码如下。面试中的test case都过了
class Solution {
public static void main(String[] args) {
boolean result = checkParantheses(")(");
System.out.println("result="+result);
}
private static boolean checkParantheses(String str){
int cnt = 0;
for(int i=0; i < str.length() ; i++){
char x = str.charAt(i);
if('(' == x){
cnt++;
}else if(')' == x){
if(cnt <=0) return false;
cnt--;
}else{
continue;
}
}
return cnt == 0 ? true : false;
}
}
面试官还问了什么时候你会用 Stack 而不是 counter?