Leetcode 395.至少有K个重复字符的最长子串

  • 找到给定字符串(由小写字符组成)中的最长子串 T , 要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。 在这里插入图片描述
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分治

class Solution {
    
    
    public int longestSubstring(String s, int k) {
    
    
        String temp = "";
        HashMap<Character, Integer> hm = new HashMap<>();//哈希map
        for (char ch : s.toCharArray()) {
    
     hm.put(ch, hm.get(ch) == null ? 1 : hm.get(ch) + 1); }//映射
        for (Character character : hm.keySet()) {
    
     if (hm.get(character) < k) temp += character; }//分割子串的依据
        char[] str = s.toCharArray();
        if (temp.equals("")) return s.length();
        else {
    
    
            int max = 0,t=-1;
            for (int i = 0; i < str.length; i++) {
    
    
                if (temp.indexOf(str[i]) != -1) {
    
    
                    max = Math.max(max, longestSubstring(s.substring(t + 1, i), k));
                    t = i;
                }
            }
            if (t != str.length - 1) max = Math.max(max, longestSubstring(s.substring(t + 1, str.length), k));
            return max;
        }
    }
}

时间复杂度:不会
空间复杂度:还不会

猜你喜欢

转载自blog.csdn.net/UZDW_/article/details/114170394