classSolution: defmaxLengthBetweenEqualCharacters(self, s: str) -> int: ans = -1 firstIndex = {} for i, c inenumerate(s): if c notin firstIndex: firstIndex[c] = i else: ans = max(ans, i - firstIndex[c] - 1) return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intmaxLengthBetweenEqualCharacters(string s){ vector<int> firstIndex(26, -1); int maxLength = -1; for (int i = 0; i < s.size(); i++) { if (firstIndex[s[i] - 'a'] < 0) { firstIndex[s[i] - 'a'] = i; } else { maxLength = max(maxLength, i - firstIndex[s[i] - 'a'] - 1); } } return maxLength; } };
funcmaxLengthBetweenEqualCharacters(s string)int { ans := -1 firstIndex := [26]int{} for i := range firstIndex { firstIndex[i] = -1 } for i, c := range s { c -= 'a' if firstIndex[c] < 0 { firstIndex[c] = i } else { ans = max(ans, i-firstIndex[c]-1) } } return ans }
funcmax(a, b int)int { if b > a { return b } return a }