【问题标题】:A performance issue with the Codility brackets challengeCodility 括号挑战的性能问题
【发布时间】: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


【解决方案1】:

作为彼得莫滕森建议。 删除“Debug.WriteLine”并在相同代码上获得 100% 的性能得分。

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 2014-12-21
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2010-12-22
    • 2021-02-10
    相关资源
    最近更新 更多