Advertisement
Guest User

nestedParens (not graded)

a guest
Jan 30th, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. static boolean nestedParens(String str)
  2. {
  3.     //base cases
  4.     //looked at whole string
  5.     if (str.length() == 0)
  6.         return true;
  7.    
  8.     //extra ')', must be false, since it does not belong to a pair
  9.     if (str.charAt(0) == ')')
  10.         return false;
  11.    
  12.     //recursive cases
  13.     if (str.charAt(0) != '(') //we don't care about non-'('s, skip it
  14.         return nestedParens(str.substring(1));
  15.    
  16.     int iCloseLoc = -1; //position of ')', -1 means not found
  17.  
  18.     for (int i = 0; i < str.length(); i++) //find ')'
  19.     {
  20.         if (str.charAt(i) == ')')
  21.         {
  22.             iCloseLoc = i;
  23.             break;
  24.         }
  25.     }
  26.            
  27.     if (iCloseLoc == -1) //did not find closing parenthesis, incomplete pair
  28.         return false;
  29.     else //found pair of parenthesis, remove them and do recursive call on new string
  30.     {  
  31.         String newStr = new String();
  32.         newStr = str.substring(1, iCloseLoc) + str.substring(iCloseLoc+1);
  33.         return nestedParens(newStr);
  34.     }  
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement