Leetcode 395. Longest Substring with At Least K Repeating Characters

Leetcode 395. Longest Substring with At Least K Repeating Characters

目前,除了递归没有想到特别好的想法去解决这个问题。
Input:
s = “ababbc”, k = 2

a->2
b->3
c->1

cur = 0, start =0;

cur = 4, map[c] < 2
result = s.substring(start, cur), return reslut.length();

public class Solution {
    public int longestSubstring(String s, int k) {
        if (s == null || s.length() == 0) return 0;
        char[] chars = new char[26];
        // record the frequency of each character
        for (int i = 0; i < s.length(); i += 1) chars[s.charAt(i) - 'a'] += 1;
        boolean flag = true;
        for (int i = 0; i < chars.length; i += 1) {
            if (chars[i] < k && chars[i] > 0) flag = false;
        }
        // return the length of string if this string is a valid string
        if (flag == true) return s.length();
        int result = 0;
        int start = 0, cur = 0;
        // otherwise we use all the infrequent elements as splits
        while (cur < s.length()) {
            if (chars[s.charAt(cur) - 'a'] < k) {
                result = Math.max(result, longestSubstring(s.substring(start, cur), k));
                start = cur + 1;
            }
            cur++;
        }
        result = Math.max(result, longestSubstring(s.substring(start), k));
        return result;
    }
}

你可能感兴趣的:(Leetcode,复习)