3035. Maximum Palindromes After Operations Medium

@problem@discussion
#Array#Hash Table#String#Greedy#Sorting#Counting



1/**
2 * [3035] Maximum Palindromes After Operations
3 *
4 * You are given a 0-indexed string array words having length n and containing 0-indexed strings.
5 * You are allowed to perform the following operation any number of times (including zero):
6 * 
7 * 	Choose integers i, j, x, and y such that 0 <= i, j < n, 0 <= x < words[i].length, 0 <= y < words[j].length, and swap the characters words[i][x] and words[j][y].
8 * 
9 * Return an integer denoting the maximum number of <span data-keyword="palindrome-string">palindromes</span> words can contain, after performing some operations.
10 * Note: i and j may be equal during an operation.
11 *  
12 * <strong class="example">Example 1:
13 * 
14 * Input: words = ["abbb","ba","aa"]
15 * Output: 3
16 * Explanation: In this example, one way to get the maximum number of palindromes is:
17 * Choose i = 0, j = 1, x = 0, y = 0, so we swap words[0][0] and words[1][0]. words becomes ["bbbb","aa","aa"].
18 * All strings in words are now palindromes.
19 * Hence, the maximum number of palindromes achievable is 3.
20 * <strong class="example">Example 2:
21 * 
22 * Input: words = ["abc","ab"]
23 * Output: 2
24 * Explanation: In this example, one way to get the maximum number of palindromes is: 
25 * Choose i = 0, j = 1, x = 1, y = 0, so we swap words[0][1] and words[1][0]. words becomes ["aac","bb"].
26 * Choose i = 0, j = 0, x = 1, y = 2, so we swap words[0][1] and words[0][2]. words becomes ["aca","bb"].
27 * Both strings are now palindromes.
28 * Hence, the maximum number of palindromes achievable is 2.
29 * 
30 * <strong class="example">Example 3:
31 * 
32 * Input: words = ["cd","ef","a"]
33 * Output: 1
34 * Explanation: In this example, there is no need to perform any operation.
35 * There is one palindrome in words "a".
36 * It can be shown that it is not possible to get more than one palindrome after any number of operations.
37 * Hence, the answer is 1.
38 *  
39 * Constraints:
40 * 
41 * 	1 <= words.length <= 1000
42 * 	1 <= words[i].length <= 100
43 * 	words[i] consists only of lowercase English letters.
44 * 
45 */
46pub struct Solution {}
47
48// problem: https://leetcode.com/problems/maximum-palindromes-after-operations/
49// discuss: https://leetcode.com/problems/maximum-palindromes-after-operations/discuss/?currentPage=1&orderBy=most_votes&query=
50
51// submission codes start here
52
53impl Solution {
54    pub fn max_palindromes_after_operations(words: Vec<String>) -> i32 {
55        0
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_3035() {
67    }
68}
69


Back
© 2025 bowen.ge All Rights Reserved.