Given a string, return true if it is a nesting of zero or more pairs of
parenthesis, like "(())" or "((()))". Suggestion: check the first and last
characters in a string and then perform recurson on what's inside them.
Examples:
nestParen("(())") returns true
nestParen("((()))") returns true
nestParen("(((x))") returns false
Solution:
public static void main(String[] args) {
//Program 7
String str = "a((xxx(abc)))bb";
System.out.println("true: " + nestParen(str));
System.out.println("true: " + nestParen("(())"));
System.out.println("true: " + nestParen("((()))"));
System.out.println("false: " + nestParen("((())"));
}
public static boolean nestParen(String str) {
//PRIMITIVE STATES:
if (!str.contains("(") && !str.contains(")"))
return true;
else if (str.length() <= 1)
return false;
else if (str.length() == 2 && (str.contains(")") || str.contains(")")))
return str.charAt(0) == '(' && str.charAt(1) == ')';
//RECURSIVE MATCH AT THE END
if (str.charAt(0) == '(' && str.charAt(str.length() -1) == ')')
return true && nestParen(str.substring(1, str.length()-1));
//REMOVE OUTER NON PARENTHESIS CHARACTERS
int s = 0;
int e = str.length();
if (str.charAt(s) != '(')
s++;
if (str.charAt(str.length()-1) != ')' && (s < e-1))
e--;
return nestParen(str.substring(s, e));
}