zoukankan      html  css  js  c++  java
  • [LeetCode 1371] Find the Longest Substring Containing Vowels in Even Counts

    Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.

     

    Example 1:

    Input: s = "eleetminicoworoep"
    Output: 13
    Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.
    

    Example 2:

    Input: s = "leetcodeisgreat"
    Output: 5
    Explanation: The longest substring is "leetc" which contains two e's.
    

    Example 3:

    Input: s = "bcbcbc"
    Output: 6
    Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.
    

     

    Constraints:

    • 1 <= s.length <= 5 x 10^5
    • s contains only lowercase English letters.

    Key observations:

    1.  For a given substring, we only care if all of its vowel counts are even. 

    2. Each time we process a new vowel character C, its count parity flips. 

    3. Even - Even = Even; Odd - Odd = Odd; Even - Odd = Odd; Odd - Even = Odd.

     

    Using the above observations, we derive the following algorithm.

    1.  Use bitmask to track s[0, i]'s vowel parity information.

    2. Each time we process a vowel, update the running bitmask by flipping this vowel's parity.

    3. For each different parity state, we save its earliest occurence in a map. For each state, if it has never appeared before, save it to the map. If it has appeared before, update the global best result. A repeating state means the substring in between its earliest and current occurence has all even counts of vowels. (Observation No. 3)

    class Solution {
        public int findTheLongestSubstring(String s) {
            Map<Integer, Integer> map = new HashMap<>();
            map.put(0, -1);
            int best = 0, curr = 0;
            for(int i = 0; i < s.length(); i++) {
                if(s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i'
                  || s.charAt(i) == 'o' || s.charAt(i) == 'u') {
                    int diff = s.charAt(i) - 'a';
                    curr ^= (1 << diff);
                }
                map.putIfAbsent(curr, i);
                best = Math.max(best, i - map.get(curr));
            }
            return best;
        }
    }

    Related Problems

    [LeetCode 525] Contiguous Array

    [LeetCode 560] Subarray Sum Equals K

    [LeetCode 1542] Find Longest Awesome Substring

  • 相关阅读:
    oracle 常用函数
    css 让div 置于最顶层而不被其他东西挡住
    hibernate学习
    css居中参考
    log4j 将日志文件输出到web-inf下的解决办法
    mybatis 传递多个值的解决办法
    web项目中的路径问题
    sring 监听器
    struts2返回json字符串
    java 需要看的书籍
  • 原文地址:https://www.cnblogs.com/lz87/p/12440647.html
Copyright © 2011-2022 走看看