比较巧妙的一道题,是练习位操作的不错的题目,解题思路很是,若两数相减为偶,则两数同奇或同偶,奇偶性质的记录可以用异或操作可以表示,另外用一个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;
}
};