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

  • 相关阅读:
    第八章 对象
    第七章 压缩列表
    第六章 整数集合
    Java中的Unsafe
    站在Java的角度看LinkedList
    Java内部类详解
    浅析Java中的final关键字
    ConcurrentHashMap
    阻塞队列
    线程池的使用和实现
  • 原文地址:https://www.cnblogs.com/lz87/p/12440647.html
Copyright © 2011-2022 走看看