1. 程式人生 > >LeetCode 3 最大不重複子串

LeetCode 3 最大不重複子串

找出最大不重複子串

關鍵在於利用雜湊表的查詢優勢,設定一個記錄不重複字串的開始位置。需要線性時間

public class Solution {
    public int LengthOfLongestSubstring(string s)
    {
        Dictionary<char,int> dict=new Dictionary<char,int>();
        int a=0,cur=0,max=0;
        for(int i=0;i<s.Length;i++)
        {
            if(!dict.Keys.Contains(s[i]))
            {
                dict.Add(s[i],i);
                cur++;
                max=max>cur?max:cur;
            }
            else
            {
                a=a<dict[s[i]]?dict[s[i]]:a;
                cur=i-a;
                max=max>cur?max:cur;
                dict[s[i]]=i;
            }
        }
        return max;
    }
}