Substring XOR Queries

Substring XOR Queries

You are given a binary string  s , and a 2D integer array queries where  queries[i] = [firsti, secondi] .

For the ith query, find the shortest substring of s whose decimal valueval , yields secondi when bitwise XORed with firsti . In other words, val ^ firsti == secondi .

The answer to the ith query is the endpoints (0-indexed) of the substring [lefti, righti] or [-1, -1] if no such substring exists. If there are multiple answers, choose the one with the minimum  lefti .

Return an array ans where ans[i] = [lefti, righti] is the answer to the ith query.

A substring is a contiguous non-empty sequence of characters within a string.

Example 1:

Input: s = "101101", queries = [[0,5],[1,2]]
Output: [[0,2],[2,3]]
Explanation: For the first query the substring in range [0,2] is "101" which has a decimal value of 5, and 5 ^ 0 = 5, hence the answer to the first query is [0,2]. In the second query, the substring in range [2,3] is "11", and has a decimal value of 3, and 3 ^ 1 = 2. So, [2,3] is returned for the second query. 

Example 2:

Input: s = "0101", queries = [[12,8]]
Output: [[-1,-1]]
Explanation: In this example there is no substring that answers the query, hence [-1,-1] is returned.

Example 3:

Input: s = "1", queries = [[4,5]]
Output: [[0,0]]
Explanation: For this example, the substring in range [0,0] has a decimal value of 1, and 1 ^ 4 = 5. So, the answer is [0,0].

Constraints:

  • $ 1 \leq \text{s.length} \leq {10}^4$
  • $s[i]$ is either $0$ or $1$.
  • $1 \leq \text{queries.length} \leq {10}^5$
  • $0 \leq \text{first}_\text{i}, \text{second}_\text{i} \leq {10}^9$

 

解题思路

  这场lc周赛跟爆零差不多,lc都打不动了好似喵。

  对于每个询问本质上就是问$s$中是否存在$\text{first}_\text{i} \wedge \text{second}_\text{i}$的二进制表示连续子串,所以想到预处理出来$s$的所有连续子串。当时没注意到询问的二进制串长度最大是$30$,一直想着这么把$s$所有的连续子串全部预处理出来。其实只用预处理出来长度不超过$30$的所有连续子串就可以了。

  比赛就是没想到询问的二进制串只用$30$,硬是不会做,好似喵。

  AC代码如下,时间复杂度为$O({30}^3 + n)$,可以优化到$O({30}^2 + n)$,懒得优化了能过就行:

 1 class Solution {
 2 public:
 3     vector<vector<int>> substringXorQueries(string s, vector<vector<int>>& queries) {
 4         int n = s.size();
 5         unordered_map<int, vector<int>> mp;
 6         for (int i = 1; i <= 30; i++) {
 7             for (int j = 0; j + i - 1 < n; j++) {
 8                 int t = 0;
 9                 for (int k = j; k <= j + i - 1; k++) {
10                     t = t << 1 | s[k] - '0';
11                 }
12                 if (!mp.count(t)) mp[t] = vector<int>({j, j + i - 1});
13             }
14         }
15         vector<vector<int>> ans(queries.size(), vector<int>(2, -1));
16         for (int i = 0; i < queries.size(); i++) {
17             int t = queries[i][0] ^ queries[i][1];
18             if (mp.count(t)) ans[i] = mp[t];
19         }
20         return ans;
21     }
22 };

 

参考资料

  枚举:https://leetcode.cn/problems/substring-xor-queries/solution/mei-ju-by-tsreaper-h2xh/

posted @ 2023-02-12 15:49  onlyblues  阅读(18)  评论(0编辑  收藏  举报
Web Analytics