leetcode395

分治法。

public class Solution
    {
        private int LongestSubstringSub(string s, int k, int start, int end)
        {
            if (start > end)
            {
                return 0;
            }
            int[] count = new int[26];
            for (int i = start; i <= end; i++)
            {
                count[s[i] - 'a']++;
            }

            for (int i = 0; i < 26; i++)
            {
                if (count[i] > 0 && count[i] < k)
                {
                    var pos = s.IndexOf((char)(i + 'a'), start);
                    return Math.Max(LongestSubstringSub(s, k, start, pos - 1), LongestSubstringSub(s, k, pos + 1, end));
                }
            }

            return end - start + 1;
        }

        public int LongestSubstring(string s, int k)
        {
            return LongestSubstringSub(s, k, 0, s.Length - 1);
        }
    }

猜你喜欢

转载自www.cnblogs.com/asenyang/p/9746685.html
今日推荐