Codibility括号挑战的性能问题



我正在努力解决Codibility括号的挑战。我的解决方案100%通过了正确性,但在性能测试中失败了。

在我看来,它应该是O(n(。

什么地方比较耗时?

  • 性能测试
  • 得分
private class Solution
{
private Stack<char> _stack = new Stack<char>();
private HashSet<char> _visited = new HashSet<char>() { '}', ']', ')' };
private Dictionary<char, char> _dictionary = new Dictionary<char, char>()
{
{ '{', '}' },
{ '[', ']' },
{ '(', ')' }
};
public int solution(String S)
{
if (S.Length % 2 != 0)
{
return 0;
}
foreach (char c in S)
{
if (_stack.Count > 0)
{
var peek = _stack.Peek();
Debug.WriteLine($"Peek: {peek} - char: {c}");
if (GetOpposite(peek).Equals(c))
{
Debug.WriteLine($"Pop {peek}");
_stack.Pop();
}
else
{
if (_visited.Contains(c))
return 0;
Debug.WriteLine($"Push: {c}");
_stack.Push(c);
}
}
else
{
if (_visited.Contains(c))
return 0;
_stack.Push(c);
}
}

return _stack.Count == 0 ? 1 : 0;
}
private char GetOpposite(char c)
{
return _dictionary[c];
}
}

正如彼得·莫滕森建议的那样。删除了";Debug.WriteLine;并且在相同的代码上获得了100%的性能分数。

最新更新