Skip to content

Commit f7f6e31

Browse files
committed
1624. Largest Substring Between Two Equal Characters: AC
1 parent 9116812 commit f7f6e31

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

src/solution/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1224,3 +1224,4 @@ mod s1619_mean_of_array_after_removing_some_elements;
12241224
mod s1620_coordinate_with_maximum_network_quality;
12251225
mod s1621_number_of_sets_of_k_non_overlapping_line_segments;
12261226
mod s1622_fancy_sequence;
1227+
mod s1624_largest_substring_between_two_equal_characters;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/**
2+
* [1624] Largest Substring Between Two Equal Characters
3+
*
4+
* Given a string s, return the length of the longest substring between two equal characters, excluding the two characters. If there is no such substring return -1.
5+
* A substring is a contiguous sequence of characters within a string.
6+
*
7+
* Example 1:
8+
*
9+
* Input: s = "aa"
10+
* Output: 0
11+
* Explanation: The optimal substring here is an empty substring between the two 'a's.
12+
* Example 2:
13+
*
14+
* Input: s = "abca"
15+
* Output: 2
16+
* Explanation: The optimal substring here is "bc".
17+
*
18+
* Example 3:
19+
*
20+
* Input: s = "cbzxy"
21+
* Output: -1
22+
* Explanation: There are no characters that appear twice in s.
23+
*
24+
*
25+
* Constraints:
26+
*
27+
* 1 <= s.length <= 300
28+
* s contains only lowercase English letters.
29+
*
30+
*/
31+
pub struct Solution {}
32+
33+
// problem: https://leetcode.com/problems/largest-substring-between-two-equal-characters/
34+
// discuss: https://leetcode.com/problems/largest-substring-between-two-equal-characters/discuss/?currentPage=1&orderBy=most_votes&query=
35+
36+
// submission codes start here
37+
38+
impl Solution {
39+
pub fn max_length_between_equal_characters(s: String) -> i32 {
40+
s.as_bytes()
41+
.into_iter()
42+
.enumerate()
43+
.fold(vec![vec![]; 26], |mut v, (ind, c)| {
44+
v[(c - b'a') as usize].push(ind as i32);
45+
v
46+
})
47+
.into_iter()
48+
.filter(|indexes| !indexes.is_empty())
49+
.map(|indexes| indexes.last().unwrap() - indexes.first().unwrap() - 1)
50+
.max()
51+
.unwrap_or(-1)
52+
}
53+
}
54+
55+
// submission codes end
56+
57+
#[cfg(test)]
58+
mod tests {
59+
use super::*;
60+
61+
#[test]
62+
fn test_1624_example_1() {
63+
let s = "aa".to_string();
64+
65+
let result = 0;
66+
67+
assert_eq!(Solution::max_length_between_equal_characters(s), result);
68+
}
69+
70+
#[test]
71+
fn test_1624_example_2() {
72+
let s = "abca".to_string();
73+
74+
let result = 2;
75+
76+
assert_eq!(Solution::max_length_between_equal_characters(s), result);
77+
}
78+
79+
#[test]
80+
fn test_1624_example_2() {
81+
let s = "cbzxy".to_string();
82+
83+
let result = -1;
84+
85+
assert_eq!(Solution::max_length_between_equal_characters(s), result);
86+
}
87+
}

0 commit comments

Comments
 (0)