I want to manipulate the given string or any string so that if every opening parenthesis has a closing parenthesis then fine. If not, I check if there are more opening parenthesis or closing parenthesis and vice versa. If opening parenthesis are more, then I insert a closing parenthesis immediately after it. If closing parenthesis are more, then I insert an opening parenthesis immediately before it.
int count1 = 0, count2 = 0;
string sentence = ") (x + 2) )(";
foreach (char letter in sentence)
{
if (letter == '(')
count1++;
else if (letter == ')')
count2++;
}
if(count1 == count2)
Console.WriteLine("Correct use of parenthesis");
else
{
if(count1 > count2)
{
//How to find which opening parenthesis is the lonely one?
}
else
{
//How to find which closing parenthesis is the lonely one?
}
}
I'm thinking of using the IndexOf method to locate the parenthesis, how to find the right parenthesis ?! A solution without using regular expression(since I still did not study them) is appreciated.
I just realized that using numbers to count the number of each parenthesis won't guarantee a correct outcome to the problem. Since a string like "( (x+2 ) (" would come out as a correct use of parenthesis. Any way to make sure the correct usage of parenthesis ?!
EDIT: So I've implemented the algorithm in the link provided by Alexei(Thanks by the way). I've a problem which is when the problem is with the opening parenthesis, the errorIndex variable is the last opening parenthesis that did not close. However, when the problem is with the closing parenthesis, the errorIndex variable is the first closing parenthesis that was not open.
This the code:
var aStack = new Stack<int>();
char openPar = '(';
char closePar = ')';
for (int index = 0; index < str.Length; index++)
{
if (str[index] == openPar)
aStack.Push(index);
else if(str[index] == closePar)
{
if(aStack.Count == 0)
{
errorIndex = index;
return false;
}
aStack.Pop();
}
}
if (aStack.Count == 0)
{
errorIndex = -1;
return true;
}
else
{
errorIndex = aStack.Peek();
return false;
}
}
In the main method, this string str1 = "(( (("; returns its error index at 4. This string str2 = ")) ))"; returns its error index at 0.