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:

  • 1s.length104
  • s[i] is either 0 or 1.
  • 1queries.length105
  • 0firsti,secondi109

 

解题思路

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

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

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

  AC代码如下,时间复杂度为O(303+n),可以优化到O(302+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 @   onlyblues  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
Web Analytics
点击右上角即可分享
微信分享提示