【5月打卡】Leetcode-1371 每個元音包含偶數次的最長子字符串

解題思路:位運算狀態壓縮+前綴和

思考過程
滑動窗口?不對,成立之時不代表後面不成立。—> 前綴和? 但是五個數咋確定偶數?—>看題解,將aeiou存在不同的二進制位上,利用異或控制字母的個數。

位運算狀態壓縮

aeiou對應5個二進制位,位數爲0(突然發現了520???)表示個數爲偶數。
當遇見a時,record=record^16=record^10000.
如果a的個數原來爲奇數,1^1=0,如果a的個數原來爲偶數,1^0=1.

前綴和

前綴和思路參考Leetcode-560 和爲K的子數組
注意有範圍時使用vector,速度遠好於map。
location[i]表示record=i的最早出現位置。
location[0]=-1,即假設s前面插入了一個虛擬字母,因爲一開始s==""時,是滿足元音均爲偶數的條件的。

class Solution {
public:
    int findTheLongestSubstring(string s) {
        int record=0,mm=0;
        vector<int> location(32,-2);
        location[0]=-1;
        for(int i=0;i<s.length();i++)
        {
            char word=s[i];
            if(word=='a')
                record^=16;   //1^1=0 
            else if(word=='e')
                record^=8;
            else if(word=='i')
                record^=4;
            else if(word=='o')
                record^=2;
            else if(word=='u')
                record^=1;
            if(location[record]!=-2)
                mm=max(mm, i-location[record]);
            else
                location[record]=i;
        }
        return mm;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章