I have a string that contains a random order of parenthesis {[()]}. I want to check if for any given parenthesis is there a matching closing one.
Example:
}}}{{{ //true {[] //false {[()]} //true
private static bool checkIfWellFormatted(string inputString)
{
if (string.IsNullOrEmpty(inputString))
throw new ArgumentException("String is empty");
if ((inputString.Length % 2) != 0)
return false;
Dictionary<char, int> _inputDictionary = new Dictionary<char, int>();
foreach (Char c in inputString)
{
if (!_inputDictionary.ContainsKey(c))
_inputDictionary.Add(c, 0);
else
_inputDictionary[c] += 1;
}
foreach (var item in _inputDictionary)
{
char oppKey = '\0';
if (item.Key == '{')
oppKey = '}';
if (item.Key == '}')
oppKey = '{';
if (item.Key == '(')
oppKey = ')';
if (item.Key == ')')
oppKey = '(';
if (item.Key == '[')
oppKey = ']';
if (item.Key == ']')
oppKey = '[';
if (_inputDictionary.ContainsKey(oppKey))
{
var value = _inputDictionary[oppKey];
if (value != item.Value)
return false;
}
else
return false;
}
return true;
}
Here, the second iteration over the dictionary has \$O(n)\$ complexity. Can I improve its time complexity?
[({])}is this a valid combination? \$\endgroup\$