Spotify | Phone screen | Verify parentheses in a string

Location: US

Given a string, which contains '(' and ')' and some other characters, verify if it is a valid parantheses. It will not contains '{' or '['.

My Solution:

Which worked for test cases tried on the call.

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;
  } 
}

Welcome your comments, or test cases which will fail it.
Anthoer question interviewer asked is, in what scenerio will you use Stack instead of a counter?

Comments (5)