Skip to content

1177. Can Make Palindrome from Substring

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) {
    vector<bool> ans;
    vector<unsigned int> dp(s.length() + 1);

    for (int i = 1; i <= s.length(); ++i)
      dp[i] = dp[i - 1] ^ 1 << s[i - 1] - 'a';

    for (const vector<int>& query : queries) {
      const int odds = popcount(dp[query[1] + 1] ^ dp[query[0]]);
      ans.push_back(odds / 2 <= query[2]);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public List<Boolean> canMakePaliQueries(String s, int[][] queries) {
    List<Boolean> ans = new ArrayList<>();
    int[] dp = new int[s.length() + 1];

    for (int i = 1; i <= s.length(); ++i)
      dp[i] = dp[i - 1] ^ 1 << s.charAt(i - 1) - 'a';

    for (int[] query : queries) {
      int odds = Integer.bitCount(dp[query[1] + 1] ^ dp[query[0]]);
      ans.add(odds / 2 <= query[2]);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def canMakePaliQueries(self, s: str, queries: list[list[int]]) -> list[bool]:
    dp = [0] * (len(s) + 1)

    for i in range(1, len(s) + 1):
      dp[i] = dp[i - 1] ^ 1 << ord(s[i - 1]) - ord('a')

    return [
        (dp[right + 1] ^ dp[left]).bit_count() // 2 <= k
        for left, right, k in queries
    ]