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 value, val , 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:
- is either or .
解题思路
这场lc周赛跟爆零差不多,lc都打不动了好似喵。
对于每个询问本质上就是问中是否存在的二进制表示连续子串,所以想到预处理出来的所有连续子串。当时没注意到询问的二进制串长度最大是,一直想着这么把所有的连续子串全部预处理出来。其实只用预处理出来长度不超过的所有连续子串就可以了。
比赛就是没想到询问的二进制串只用,硬是不会做,好似喵。
AC代码如下,时间复杂度为,可以优化到,懒得优化了能过就行:
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/
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17113933.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效