1177. 构建回文串检测
题目描述
给你一个字符串 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,可以认为每次检测都是独立的)
来源:力扣(LeetCode)
我的题解思路–java实现
思路很简单:有提到可以随意调换位置。那么回文串的特点就变成了了只要有两个一样的字母,就可以摆在正确的位置上。那我们只需要计算子串中的奇数个字母出现的个数即可。
我们最多可以替换K个字母。所以只要最后只要奇数个数的字母不超过2k个,就可以构成回文字符串。
解法一:用到了map来记数,在这道题里没有数组简单。(最后31个样例只通过了29个。超时了)
public List<Boolean> canMakePaliQueries(String s, int[][] queries) {
List<Boolean> result=new ArrayList<>();
for(int i=0;i<queries.length;i++){
String tmps=s.substring(queries[i][0],queries[i][1]+1);
int k=queries[i][2];
Map<Character,Integer> map=new HashMap<>();
for(int j=0;j<tmps.length();j++){
Character ch=tmps.charAt(j);
if(map.containsKey(ch)){
map.put(ch,map.get(ch)+1);
}else{
map.put(ch,1);
}
}
int t=0;
for(Integer value:map.values()){
if(value%2!=0){
t++;
}
}
if(t <=2*k+1){
result.add(true);
}else{
result.add(false);
}
}
return result;
}
解法二:最后通过看题解,才知道了可以先进行记数,最后针对要查询的子串,直接计算出结果就行。
先用二维数据存起来从0到当前位置的所有字母出现次数的累加。
知识点:
System.arraycopy(count[i],0,count[i+1],0,26);`
把count[i]从第0个位置开始复制到count[i+1]数组的从第0个位置起的地方。一共复制26个长度。
public List<Boolean> canMakePaliQueries(String s, int[][] queries) {
List<Boolean> result=new ArrayList<>();
char[] ss = s.toCharArray();
int n=ss.length;
int[][] count=new int[n+1][26];
for(int i=0;i<n;i++){
char ch=ss[i];
System.arraycopy(count[i],0,count[i+1],0,26);
count[i+1][ch-'a']++;
}
for(int i=0;i<queries.length;i++){
int start=queries[i][0];
int end=queries[i][1]+1;
int k=queries[i][2];
int[] cnt=new int[26];
for(int j=0;j<26;j++){
cnt[j]=count[end][j]-count[start][j];
}
int t=0;
for(int value:cnt){
if(value%2!=0){
t++;
}
}
if(t <=2*k+1){
result.add(true);
}else{
result.add(false);
}
}
return result;
}