Leetcode 1177 构建回文串检测 (C++题解)
给你一个字符串 s,请你对 s 的子串进行检测。
每次检测,待检子串都可以表示为 queries[i] = [left, right, k]。我们可以 重新排列 子串 s[left], ..., s[right],并从中选择 最多 k 项替换成任何小写英文字母。
如果在上述检测过程中,子串可以变成回文形式的字符串,那么检测结果为 true,否则结果为 false。
返回答案数组 answer[],其中 answer[i] 是第 i 个待检子串 queries[i] 的检测结果。
注意:在替换时,子串中的每个字母都必须作为 独立的 项进行计数,也就是说,如果 s[left..right] = "aaa" 且 k = 2,我们只能替换其中的两个字母。(另外,任何检测都不会修改原始字符串 s,可以认为每次检测都是独立的)
示例:
输入:s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]
输出:[true,false,false,true,true]
解释:
queries[0] : 子串 = "d",回文。
queries[1] : 子串 = "bc",不是回文。
queries[2] : 子串 = "abcd",只替换 1 个字符是变不成回文串的。
queries[3] : 子串 = "abcd",可以变成回文的 "abba"。 也可以变成 "baab",先重新排序变成 "bacd",然后把 "cd" 替换为 "ab"。
queries[4] : 子串 = "abcda",可以变成回文的 "abcba"。
提示:
1 <= s.length, queries.length <= 10^5
0 <= queries[i][0] <= queries[i][1] < s.length
0 <= queries[i][2] <= s.length
s 中只有小写英文字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/can-make-palindrome-from-substring
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:借用别人的经验:
该题本身不难,但是需要注意时间复杂度。
求字符串变为回文字符串时,所需要进行替换字符的最小数目,通过求得字母统计中数目为奇数的字符数目odd。
如果字符串长度为奇数,则最少需要将(odd-1)/2(odd−1)/2个字符进行替换,如果字符串长度为偶数,则最少需要将odd/2odd/2个字符进行替换。
我们采用滑动窗口来求出字符串的字符统计,同时进行判定给定的k的是否大于最小数目
[code]class Solution { public: int replace(vector<int> &l,vector<int> &r,int sz){ int odd = 0; for(int i = 0;i < 26; ++i){ if((r[i] - l[i])%2){ odd++; } } if(sz%2 == 0){ return odd/2; }else{ return (odd-1)/2; } } vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) { int n = s.size(); int m = queries.size(); vector<bool> ans(m,false); vector<vector<int>> dp(n+1,vector<int>(26,0)); for(int i = 0;i < n; ++i){ dp[i+1] = dp[i]; dp[i+1][s[i]-'a']++; } for(int i = 0;i < m; ++i){ int l = queries[i][0]; int r = queries[i][1]; int rep = replace(dp[l],dp[r+1],r+1-l); if(rep <= queries[i][2]){ ans[i] = true; } } return ans; } };
- LeetCode 268. Missing Number 题解(C++)
- LeetCode 13. Roman to Integer 题解(C++)
- LeetCode 389. Find the Difference 题解(C++)
- LeetCode 260. Single Number III 题解(C++)
- [LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
- LeetCode 436. Find Right Interval 题解(C++)
- LeetCode 413. Arithmetic Slices 题解(C++)
- LeetCode 452. Minimum Number of Arrows to Burst Balloons 题解(C++)
- LeetCode 104. Maximum Depth of Binary Tree 题解(C++)
- LeetCode 100. Same Tree 题解(C++)
- LeetCode 357. Count Numbers with Unique Digits 题解(C++)
- LeetCode 436. Find Right Interval 题解(C++)
- LeetCode 419. Battleships in a Board 题解(C++)
- LeetCode 217. Contains Duplicate 题解(C++)
- LeetCode题解(C++版)
- LeetCode 226. Invert Binary Tree 题解(C++)
- Leetcode 079 搜索单词 Python C++ 史上最详细题解系列
- Leetcode 312 打气球 Burst Balloons C++ 史上最详细题解系列
- LeetCode 318. Maximum Product of Word Lengths 题解(C++)
- LeetCode 122. Best Time to Buy and Sell Stock II 题解(C++)