|
| 1 | +/** |
| 2 | + * 1177. Can Make Palindrome from Substring |
| 3 | + * https://leetcode.com/problems/can-make-palindrome-from-substring/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given a string s and array queries where queries[i] = [lefti, righti, ki]. We may |
| 7 | + * rearrange the substring s[lefti...righti] for each query and then choose up to ki of them |
| 8 | + * to replace with any lowercase English letter. |
| 9 | + * |
| 10 | + * If the substring is possible to be a palindrome string after the operations above, the |
| 11 | + * result of the query is true. Otherwise, the result is false. |
| 12 | + * |
| 13 | + * Return a boolean array answer where answer[i] is the result of the ith query queries[i]. |
| 14 | + * |
| 15 | + * Note that each letter is counted individually for replacement, so if, for example |
| 16 | + * s[lefti...righti] = "aaa", and ki = 2, we can only replace two of the letters. Also, note |
| 17 | + * that no query modifies the initial string s. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {string} s |
| 22 | + * @param {number[][]} queries |
| 23 | + * @return {boolean[]} |
| 24 | + */ |
| 25 | +var canMakePaliQueries = function(s, queries) { |
| 26 | + const prefixCounts = new Array(s.length + 1).fill().map(() => new Array(26).fill(0)); |
| 27 | + |
| 28 | + for (let i = 0; i < s.length; i++) { |
| 29 | + prefixCounts[i + 1] = [...prefixCounts[i]]; |
| 30 | + prefixCounts[i + 1][s.charCodeAt(i) - 97]++; |
| 31 | + } |
| 32 | + |
| 33 | + const getOddCount = (left, right) => { |
| 34 | + let odds = 0; |
| 35 | + for (let j = 0; j < 26; j++) { |
| 36 | + const count = prefixCounts[right + 1][j] - prefixCounts[left][j]; |
| 37 | + odds += count % 2; |
| 38 | + } |
| 39 | + return odds; |
| 40 | + }; |
| 41 | + |
| 42 | + const result = queries.map(([left, right, k]) => { |
| 43 | + const oddCount = getOddCount(left, right); |
| 44 | + return oddCount <= 2 * k + 1; |
| 45 | + }); |
| 46 | + |
| 47 | + return result; |
| 48 | +}; |
0 commit comments