Capital One Interview Question

Validate the parenthesis in a string ensuring that all open parenthesis have a matching closing.

Interview Answers

Anonymous

Oct 26, 2016

Gave several ways to solve this problem, it is widely used as an interview question so I was very prepared for it. Solved with a stack, recursion, counter, and a mix then chose the best solution and explained why.

Anonymous

Feb 8, 2017

Stack parens = new Stack(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') parens.push(c); else if (c == ')' && !parens.empty() && parens.peek() == '(') parens.pop(); else if (c == ']' && !parens.empty() && parens.peek() == '[') parens.pop(); else if (c == '}' && !parens.empty() && parens.peek() == '{') parens.pop(); else return false; } return parens.empty();