I would greatly appreciate if you could help me with this in Java.
Given two Strings, lets say String A = "(A+B)+(C)" and String B = "((A+B)+(C))" and String C = (A+B) and String D = A+(B+C) and String E = (A+(B+C))
How can I identify if the String is completely surrounded by parenthesis like String B.
In example: boolean flag(String expr) { //return false if surrounded, else true }
If expr = A, flag would return true
If expr = B, flag would return false
If expr = C, flag would return false
If expr = D, flag would return true
If expr = E, flag would return flase
Sorry if it isn’t clear, but it should work for any String expression:
Assume the expression contains only Digits and Operators and Parenthesis.
Thanks. Appreciate it.
You can’t do it* with a regular expression because nested parentheses isn’t a regular language.
Instead iterate over the string and keep track of the nesting level by counting the number of opening and closing parentheses. For each opening parenthesis add one to the nesting level. For each closing parenthesis subtract one.
Here are some worked examples to demonstrate the principle:
*sanely