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.

相似题型:LeetCode题解 – 字符串和数组(560)

Presum + HashMap

Presum的方法只能适用与substring相关的题目

时间复杂度:O(n)
空间复杂度:O(32)

public int findTheLongestSubstring(String s) {
        int length = s.length();
        char[] vowels = new char[]{'a','e','i','o','u'};
        Map<Integer,Integer> index = new HashMap<>();
        index.put(0,-1);
        int max = 0;
        int state = 0;

        for(int i = 0;i < length;i++){
            for(int j = 0;j < vowels.length;j++) {
                if (s.charAt(i) == vowels[j]) {
                    state ^= 1 << j;
                }
            }
            index.putIfAbsent(state,i);
            max = Math.max(max, i - index.get(state));
        }

        return max;
    }

你可能感兴趣的:(字符串和数组)