|
| 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