LeetCode 395 Longest Substring with At Least K Repeating Characters

来源:互联网 发布:mysql数据库存储过程 编辑:程序博客网 时间:2024/06/16 05:17

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:

Input:s = "aaabb", k = 3Output:3The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input:s = "ababbc", k = 2Output:5The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

Runtime: 3 ms

public int longestSubstring(String s, int k) {if (s == null || s.length() == 0) return 0;int[] nums = new int[26];char[] chars = s.toCharArray();for (char c : chars) nums[c - 'a']++;boolean valid = false, flag = false;for (int num : nums) {if (num >= k) valid = true;if (num > 0 && num < k) flag = true;if (valid && flag) break;}if (!valid) return 0;// invalid: no char in s appears >= k times.if (!flag) return s.length();//!flag: every char appears >= k times.int max = 0, start = 0, cur = 0;for (int i = 0; i < s.length(); i++) {if (nums[chars[i] - 'a'] < k) {max = Math.max(max, longestSubstring(s.substring(start, i), k));start = i + 1;}}max = Math.max(max, longestSubstring(s.substring(start), k));return max;}


0 0
原创粉丝点击