jobPrep
BAN USER- 0of 0 votes
AnswersInput any string, count the maximum depth of parenthesis nesting, i.e. "abc(123(xyz))m(((n)))o" -> 3.
- jobPrep in United States
if input is null or contains a mismatch "a)b(c" or "a(b"
Also some other samples:
(((()))) -> 4
()()()() -> 1| Report Duplicate | Flag | PURGE
Walmart Labs Coding
This solve was something I was trying for. I like the solve, except that it does not take care of the input= ")()(" or "()(("
So I debugged and fixed it this way.
public static void main(String args[]){
// System.out.println(nestedParenthesisDepth("abc(123(xyz))m(((n)))o"));
System.out.println(nestedParenthesisDepth(")()("));
// System.out.println(nestedParenthesisDepth("()()()()("));
// System.out.println(nestedParenthesisDepth("((()))()()"));
}
/**
* Count the maximum depth of parenthesis nesting, i.e. "abc(123(xyz))m(((n)))o" -> 3.
*
* @param input
* any string
* @return deepest parenthesization level
* @throws IllegalArgumentException
* if input is null or contains a mismatch "a)b(c" or "a(b"
*/
public static int nestedParenthesisDepth(String input)
throws IllegalArgumentException {
int maxcount = 0;
int par_count = 0;
for(int i=0; i<input.length(); i++){
if(input.charAt(i) == '('){
par_count++;
if(par_count > maxcount){
maxcount = par_count;
}
}else if(input.charAt(i) == ')'){
if(par_count > 0){
par_count--;
}
}
}
if(par_count!=0){
throw new IllegalArgumentException();
}
return maxcount;
}
}
- jobPrep February 23, 2015