Skip to content

1542. Find Longest Awesome Substring 👍

  • Time: $O(10n) = O(n)$
  • Space: $O(1024) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int longestAwesome(string s) {
    int ans = 0;
    int prefix = 0;  // the binary prefix
    vector<int> prefixToIndex(1024, s.length());
    prefixToIndex[0] = -1;

    for (int i = 0; i < s.length(); ++i) {
      prefix ^= 1 << s[i] - '0';
      ans = max(ans, i - prefixToIndex[prefix]);
      for (int j = 0; j < 10; ++j)
        ans = max(ans, i - prefixToIndex[prefix ^ 1 << j]);
      prefixToIndex[prefix] = min(prefixToIndex[prefix], i);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int longestAwesome(String s) {
    int ans = 0;
    int prefix = 0; // the binary prefix
    int[] prefixToIndex = new int[1024];
    Arrays.fill(prefixToIndex, s.length());
    prefixToIndex[0] = -1;

    for (int i = 0; i < s.length(); ++i) {
      prefix ^= 1 << s.charAt(i) - '0';
      ans = Math.max(ans, i - prefixToIndex[prefix]);
      for (int j = 0; j < 10; ++j)
        ans = Math.max(ans, i - prefixToIndex[prefix ^ 1 << j]);
      prefixToIndex[prefix] = Math.min(prefixToIndex[prefix], i);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def longestAwesome(self, s: str) -> int:
    ans = 0
    prefix = 0  # the binary prefix
    prefixToIndex = [len(s)] * 1024
    prefixToIndex[0] = -1

    for i, c in enumerate(s):
      prefix ^= 1 << int(c)
      ans = max(ans, i - prefixToIndex[prefix])
      for j in range(10):
        ans = max(ans, i - prefixToIndex[prefix ^ 1 << j])
      prefixToIndex[prefix] = min(prefixToIndex[prefix], i)

    return ans