github_34366006
github_34366006
2016-03-20 17:18

Leetcode第三题,本地运行72ms,为何提交后TLE?

  • c#
  • leetcode

题目链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
使用了HashSet,会不会是因为Mono的HashSet实现比微软的性能差很多?本地跑相同测试用例只用了72ms,提交后还是TLE
代码如下:

        public int LengthOfLongestSubstring(string s)
        {
            if (s.Length <= 1)
            {
                return s.Length;
            }
            int length = 0;
            for (int i = 0; i < s.Length; i++)
            {
                HashSet<char> set = new HashSet<char>();
                for (int j = 0; i + j < s.Length; j++)
                {
                    int offset = 0;
                    if ((offset = Add(set, s[i + j])) != -1)
                    {
                        length = length > j ? length : j;
                        i += offset;
                        break;
                    }
                }
            }
            return length;
        }

        public int Add(HashSet<char> set, char ch)
        {
            if (!set.Add(ch))
            {
                for (int i = 0; i < set.Count; i++)
                {
                    if (set.ElementAt(i) == ch)
                    {
                        return i + 1;
                    }
                }
            }
            return -1;
        }
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答