leetcode周赛152-5175构建回文串检测

题目描述:

  给你一个字符串 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 中只有小写英文字母

解题思路:

  思路1:采用暴力匹配的方式,使用substring 函数对 queries[0]~queries[1]的字符串的进行切分返回,然后进行不同字母的个数统计,如:a的个数为1,b的个数为1,c的个数为2,因此需要替换的的need_k 为1,也就是将a->b 或者 b->a即可构成回文数 cbbc 或者caac。但可能出现timeout limit 情况

  思路2:使用一个字典保存当前字符串所因为0~0 0~1 0~2 ... 0~n的字符统计(dic[n][26]),想要获取start~end ,使用 dic[end][0~26] - dic[start-1][0~26] 即可得到相应区间的字符统计。然后对字符进行奇偶数的统计,即可得出替换字符字符的个数。此方法为动态规划算法,避免出现超时

 

源码展示:

  思路1:

    略!

       思路2:

    

 1 public List canMakePaliQueries(String s, int[][] queries) {
 2 
 3         List list = new ArrayList<>();
 4 
 5         char[] s_arr = s.toCharArray();
 6         //记录前n个字符个数统计
 7         int[][] dic = new int[s.length()][26];
 8         for(int i = 0; i < s_arr.length ; i++){
 9             if(i > 0){
10                 dic[i] = dic[i -1].clone();
11             }
12             dic[i][s_arr[i] - 'a']++;
13         }
14 
15         for(int i = 0; i< queries.length ; i++){
16             //判断需要几个替换位置
17             int need_k = getnum(dic , queries[i][0] , queries[i][1]);
18 
19             //替换位置是否足够
20             if(need_k <= queries[i][2]){
21                 list.add(true);
22             }else{
23                 list.add(false);
24             }
25         }
26 
27         return list;
28 
29     }
30 
31     public int getnum(int[][] dic ,int start , int end){
32 
33         int res = 0;
34         if(start == 0){
35             for(int i = 0;i < 26 ; i ++){
36                 if((dic[end][i]) % 2 != 0){
37                     res ++;
38                 }
39             }
40         }else {
41             for(int i = 0;i < 26 ; i ++){
42                 if((dic[end][i] - dic[start - 1][i]) % 2 != 0){
43                     res ++;
44                 }
45             }
46         }
47 
48 
49         return res/2;
50     }

 

转载于:https://www.cnblogs.com/oldhands/p/11442566.html

你可能感兴趣的:(leetcode周赛152-5175构建回文串检测)