4、无重复字符的最长子串

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
 class Program
    {
        static void Main(string[] args)
        {
           var t=  ComputeString.ComputeM("bacdcab");

            Console.WriteLine(t);
            Console.ReadKey();
        }
    }




    class ComputeString
    {
        public static int ComputeM(string str)
        {
            int len = str.Length;

            HashSet<char> set = new HashSet<char>();

            int ans=0, start = 0, end = 0;

            while (start < len && end < len)
            {
                if (!set.Contains(str[end]))
                {
                    set.Add(str[end++]);
                    ans = Math.Max(ans, end - start);
                }
                else
                {
                    set.Remove(str[start++]);
                }
            }

            return ans;
        }

        public static int LengthOfLongestSubstring(string s)
        {
            //字符串转化为char[]数组
            var array = s.ToCharArray();
            int n = array.Length, ans = 0;
            Dictionary<char, int> map = new Dictionary<char, int>();

            for (int j = 0, i = 0; j < n; j++)
            {
                if (map.ContainsKey(array[j]))
                {
                    //map[array[j]]
                    //i(赋值号两边)
                    i = Math.Max(map[array[j]], i);
                }
                ans = Math.Max(ans, j - i + 1);
                map[array[j]] = j + 1;
            }
            return ans;
        }
    }

  

原文地址:https://www.cnblogs.com/coderblog/p/10858097.html