首页 > 解决方案 > 我是否将滑动窗口增加得太远了?

问题描述

我正在努力解决LeetCode 上的这个问题,它找到给定字符串的最长子字符串而不重复字符。我的解决方案适用于某些字符串(例如'pwwkew'),但不适用于其他字符串(例如'ckilbkd')。有什么建议么?

public int LengthOfLongestSubstring(string s) {
    if (s.Length < 2) return s.Length;

    HashSet<char> existing = new HashSet<char>();
    Stack<string> vals = new Stack<string>();

    int start = 0;
    int end = 1;
    int result = 1;
    existing.Add(s[0]);

    while (end < s.Length && start < end)
    {
        if (!existing.Contains(s[end]))
        {
            if (end == (s.Length - 1))
            {
                result = s.Length - start;
                Console.WriteLine("here");
                break;
            }

            existing.Add(s[end]);
            end++;
        }
        else
        {
            var res = s.Substring(start, end - start);

            if (vals.Count == 0)
            {
                vals.Push(res);
                result = res.Length;
            }
            else if (res.Length > vals.Peek().Length)
            {
                vals.Pop();
                vals.Push(res);
                result = res.Length;
            }

            if (s[end] == s[end - 1])
            {
                start = end;
                end++;
            }
            else
                start++;
        }
    }

    return result;
}

标签: c#algorithmsliding-window

解决方案


推荐阅读