# 兩個相等字符的Leetcode解決方案之間的最大子字符串

`s = "aa"`
`0`

`s = "abca"`
`2`

## 兩個相等字符之間的最大子字符串的代碼Leetcode解決方案

### C ++代碼

```#include <bits/stdc++.h>
using namespace std;

int maxLengthBetweenEqualCharacters(string s) {
vector<int> f1(26, -1), f2(26, -1);
int n = s.size();
for(int i=0;i<n;i++){
if(f1[s[i]-'a'] == -1)
f1[s[i]-'a'] = i;
else
f2[s[i]-'a'] = i;
}

int ans = -1;
for(int i=0;i<26;i++)
if(f2[i] != -1)
ans = max(ans, f2[i]-f1[i]-1);
return ans;
}

int main(){
cout<<maxLengthBetweenEqualCharacters("aa");
}
```
`0`

### Java代碼

```import java.util.*;
import java.lang.*;
import java.io.*;

class Main
{
public static int maxLengthBetweenEqualCharacters(String s) {
int[] f1 = new int[26];
int[] f2 = new int[26];
for(int i=0;i<26;i++){
f1[i] = -1;
f2[i] = -1;
}
int n = s.length();
for(int i=0;i<n;i++){
if(f1[s.charAt(i)-'a'] == -1)
f1[s.charAt(i)-'a'] = i;
else
f2[s.charAt(i)-'a'] = i;
}

int ans = -1;
for(int i=0;i<26;i++)
if(f2[i] != -1)
ans = Math.max(ans, f2[i]-f1[i]-1);
return ans;
}

public static void main (String[] args) throws java.lang.Exception
{
String s = "aa";
System.out.print(maxLengthBetweenEqualCharacters(s));
}
}```
`0`

## 複雜度分析

### 空間複雜度

O（1）， 因為我們使用了恆定大小的數組。