2023-12-31 Daily Challenge

Today I have done leetcode's December LeetCoding Challenge with cpp.

December LeetCoding Challenge 31

Description

Largest Substring Between Two Equal Characters

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.

A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: s = "aa"
Output: 0
Explanation: The optimal substring here is an empty substring between the two 'a's.

Example 2:

Input: s = "abca"
Output: 2
Explanation: The optimal substring here is "bc".

Example 3:

Input: s = "cbzxy"
Output: -1
Explanation: There are no characters that appear twice in s.

 

Constraints:

  • 1 <= s.length <= 300
  • s contains only lowercase English letters.

Solution

int front[26];
int back[26];
class Solution {
public:
  int maxLengthBetweenEqualCharacters(string s) {
    for(int i = 0; i < 26; ++i) {
      front[i] = 1000;
      back[i] = -1000;
    }
    for(int i = 0; i < s.length(); ++i) {
      int c = s[i] - 'a';
      front[c] = min(front[c], i);
      back[c] = max(back[c], i);
    }
    int answer = -1;
    for(int i = 0; i < 26; ++i) {
      answer = max(answer, back[i] - 1 - front[i]);
    }
    return answer;
  }
};

// Accepted
// 54/54 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 97.01 % of cpp submissions (6.6 MB)