【发布时间】:2022-10-04 22:00:24
【问题描述】:
我正在尝试解决Codility brackets 挑战。 我的解决方案是通过正确性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'行?或者相反,它们是必需的吗? (不是反问。) -
这不是 Java:
$在Debug.WriteLine($"foobar");中做什么?foreach不是 Java 中的有效关键字。字符串没有隐式关键字Length,而是一个方法length()。您能否添加正确的语言标签或将其添加到您的问题中?
标签: c# .net performance