Skip to content

Commit aeb0ce9

Browse files
committed
1542. Find Longest Awesome Substring: AC
1 parent ce72ca6 commit aeb0ce9

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

src/solution/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1163,3 +1163,4 @@ mod s1537_get_the_maximum_score;
11631163
mod s1539_kth_missing_positive_number;
11641164
mod s1540_can_convert_string_in_k_moves;
11651165
mod s1541_minimum_insertions_to_balance_a_parentheses_string;
1166+
mod s1542_find_longest_awesome_substring;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
/**
2+
* [1542] Find Longest Awesome Substring
3+
*
4+
* You are given a string s. An awesome substring is a non-empty substring of s such that we can make any number of swaps in order to make it a palindrome.
5+
* Return the length of the maximum length awesome substring of s.
6+
*
7+
* Example 1:
8+
*
9+
* Input: s = "3242415"
10+
* Output: 5
11+
* Explanation: "24241" is the longest awesome substring, we can form the palindrome "24142" with some swaps.
12+
*
13+
* Example 2:
14+
*
15+
* Input: s = "12345678"
16+
* Output: 1
17+
*
18+
* Example 3:
19+
*
20+
* Input: s = "213123"
21+
* Output: 6
22+
* Explanation: "213123" is the longest awesome substring, we can form the palindrome "231132" with some swaps.
23+
*
24+
*
25+
* Constraints:
26+
*
27+
* 1 <= s.length <= 10^5
28+
* s consists only of digits.
29+
*
30+
*/
31+
pub struct Solution {}
32+
33+
// problem: https://leetcode.com/problems/find-longest-awesome-substring/
34+
// discuss: https://leetcode.com/problems/find-longest-awesome-substring/discuss/?currentPage=1&orderBy=most_votes&query=
35+
36+
// submission codes start here
37+
38+
impl Solution {
39+
pub fn longest_awesome(s: String) -> i32 {
40+
let mut map = std::collections::HashMap::new();
41+
let mut mask = 0;
42+
let mut result = 0;
43+
44+
map.insert(0, -1);
45+
46+
for (i, c) in s.bytes().enumerate() {
47+
mask ^= 1 << (c - b'0');
48+
if let Some(&j) = map.get(&mask) {
49+
result = result.max(i as i32 - j);
50+
}
51+
for k in 0..10 {
52+
let mask2 = mask ^ (1 << k);
53+
if let Some(&j) = map.get(&mask2) {
54+
result = result.max(i as i32 - j);
55+
}
56+
}
57+
map.entry(mask).or_insert(i as i32);
58+
}
59+
60+
result
61+
}
62+
}
63+
64+
// submission codes end
65+
66+
#[cfg(test)]
67+
mod tests {
68+
use super::*;
69+
70+
#[test]
71+
fn test_1542_example_1() {
72+
let s = "3242415".to_string();
73+
74+
let result = 5;
75+
76+
assert_eq!(Solution::longest_awesome(s), result);
77+
}
78+
79+
#[test]
80+
fn test_1542_example_2() {
81+
let s = "12345678".to_string();
82+
83+
let result = 1;
84+
85+
assert_eq!(Solution::longest_awesome(s), result);
86+
}
87+
88+
#[test]
89+
fn test_1542_example_3() {
90+
let s = "213123".to_string();
91+
92+
let result = 6;
93+
94+
assert_eq!(Solution::longest_awesome(s), result);
95+
}
96+
}

0 commit comments

Comments
 (0)