LeetCode 2272. Substring With Largest Variance
原题链接在这里:https://leetcode.com/problems/substring-with-largest-variance/
题目:
The variance of a string is defined as the largest difference between the number of occurrences of any 2
characters present in the string. Note the two characters may or may not be the same.
Given a string s
consisting of lowercase English letters only, return the largest variance possible among all substrings of s
.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it.
Example 2:
Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0.
Constraints:
1 <= s.length <= 104
s
consists of lowercase English letters.
题解:
The variance is the difference between largest char occurance - smallest char occurance.
We could mark most apparence char as 1, lest appearence char as -1.
aaaab would be like [1, 1, 1, 1, -1]. Then this question would be like maximum subarray.
However it needs to have at least one b since aaaa is not a valid case.
How to make sure there is at least one b, update the result when count of b is larger than 0.
When count of a is already smaller than count of b, we need to reset count of a and count of b as 0. However, it must make sure there is more b in the rest string.
Since baaa, at the first char b, count of b is 1, count of a is 0. Should we reset? No. If we reset there would never be a b in the rest and aaa is not a solid case.
Time Complexity: O(n). 26 * 26 * n. n = s.length().
Space: O(1).
AC Java:
1 class Solution { 2 public int largestVariance(String s) { 3 if(s == null || s.length() == 0){ 4 return 0; 5 } 6 7 int [] map = new int[26]; 8 for(int i = 0; i < s.length(); i++){ 9 map[s.charAt(i) - 'a']++; 10 } 11 12 int res = 0; 13 for(int i = 0; i < 26; i++){ 14 for(int j = 0; j < 26; j++){ 15 if(map[i] == 0 || map[j] == 0 || i == j){ 16 continue; 17 } 18 19 int countI = 0; 20 int countJ = 0; 21 int remainJ = map[j]; 22 for(int k = 0; k < s.length(); k++){ 23 int ind = (int)(s.charAt(k) - 'a'); 24 if(ind == i){ 25 countI++; 26 }else if(ind == j){ 27 countJ++; 28 remainJ--; 29 } 30 31 if(countI > countJ && countJ > 0){ 32 res = Math.max(res, countI - countJ); 33 } 34 35 if(countI < countJ && remainJ > 0){ 36 countI = 0; 37 countJ = 0; 38 } 39 } 40 } 41 } 42 43 return res; 44 } 45 }