Suppose I have a string "(paid for) + (8 working hours) + (company rules)" . Now I want to check whether this complete string is surrounded with parentheses or not. Basically I want to check if the string is like this or not : "((paid for) + (8 working hours) + (company rules))". If it is already surrounded with parentheses, then I will leave it as it is, otherwise I will apply parentheses to the complete string so that the ouput is : "((paid for) + (8 working hours) + (company rules))" . By counting the number of parentheses, I am not able to solve this problem.
Can anyone please suggest a solution?
The Stack
is a good idea, but as you want to see if the complete string is surrounded with parens, i suggest you put the index of the encountered opening paren on the Stack
. That way, each time you pop an item on the stack, check if it's 0
, meaning the opening paren that corresponds to this closing paren was on the beginning of the string. The result of this check for the last closing paren will tell you if you need to add parens.
Example:
String s = "((paid for) + (8 working hours) + (company rules))";
var stack = new Stack<int>();
bool isSurroundedByParens = false;
for (int i = 0; i < s.Length; i++) {
switch (s[i]) {
case '(':
stack.Push(i);
isSurroundedByParens = false;
break;
case ')':
int index = stack.Any() ? stack.Pop() : -1;
isSurroundedByParens = (index == 0);
break;
default:
isSurroundedByParens = false;
break;
}
}
if (!isSurroundedByParens) {
// surround with parens
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With