Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static boolean nestedParens(String str)
- {
- //base cases
- //looked at whole string
- if (str.length() == 0)
- return true;
- //extra ')', must be false, since it does not belong to a pair
- if (str.charAt(0) == ')')
- return false;
- //recursive cases
- if (str.charAt(0) != '(') //we don't care about non-'('s, skip it
- return nestedParens(str.substring(1));
- int iCloseLoc = -1; //position of ')', -1 means not found
- for (int i = 0; i < str.length(); i++) //find ')'
- {
- if (str.charAt(i) == ')')
- {
- iCloseLoc = i;
- break;
- }
- }
- if (iCloseLoc == -1) //did not find closing parenthesis, incomplete pair
- return false;
- else //found pair of parenthesis, remove them and do recursive call on new string
- {
- String newStr = new String();
- newStr = str.substring(1, iCloseLoc) + str.substring(iCloseLoc+1);
- return nestedParens(newStr);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement