leetcode记录——每个元音包含偶数次的最长子字符串

比较巧妙的一道题,是练习位操作的不错的题目,解题思路很是,若两数相减为偶,则两数同奇或同偶,奇偶性质的记录可以用异或操作可以表示,另外用一个hash表来表示各种奇偶情况对应的最短的子字符串长度,然后在下一次出现相同奇偶情况时,去减去相对应的最短子字符串长度,这样就可以保证减出来的结果中,每个元音都出现偶数次了,然后把其中长度最长的return出来即可,代码:

class Solution {

public:

    int findTheLongestSubstring(string s) {

        vector<int> record_list(32, -2);

        int status = 0, result = 0;

        record_list[0] = -1;

        for (int i = 0; i < s.length(); i ++) {

            if (s[i] == 'a')

                status ^= 1 << 0;

            if (s[i] == 'e')

                status ^= 1 << 1;

            if (s[i] == 'i')

                status ^= 1 << 2;

            if (s[i] == 'o')

                status ^= 1 << 3;

            if (s[i] == 'u')

                status ^= 1 << 4;

            if (record_list[status] >= -1)

                result = max(result, i - record_list[status]);

            else

                record_list[status] = i;

        }

        return result;

    }

};

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。