思路:

整体思路是从前向后扫描,用前缀和思想和map(hashmap)来查找符合要求的最长子串。具体实现的时候使用了二进制位状态压缩技术来表示前缀和。

实现:

 1 class Solution
 2 {
 3 public:
 4     int longestAwesome(string s)
 5     {
 6         int n = s.length(), cnt = 0, ans = 0;
 7         unordered_map<int, int> mp;
 8         mp[0] = -1;
 9         for (int i = 0; i < n; i++)
10         {
11             int t = s[i] - '0';
12             cnt ^= 1 << t;
13             if (mp.count(cnt))
14             {
15                 int pos = mp[cnt];
16                 ans = max(ans, i - pos);
17             }
18             for (int j = 0; j < 10; j++)
19             {
20                 t = 1 << j;
21                 int need = cnt ^ t;
22                 if (mp.count(need))
23                 {
24                     int pos = mp[need];
25                     ans = max(ans, i - pos);
26                 }
27             }
28             if (!mp.count(cnt)) mp[cnt] = i;
29         }
30         return ans;
31     }
32 };

相关文章:

  • 2021-10-28
  • 2021-10-27
  • 2021-10-03
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2022-12-23
相关资源
相似解决方案