Given a string
A substring is a contiguous sequence of characters within 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 = "abca"
Output: 2
Approach
Java
import java.util.ArrayList;import java.util.Collections;import java.util.List;public class LargestSubstringEqualChar {public static void main(String[] args) {String str = "abca";System.out.println(maxLengthBetweenEqualCharacters(str));}static int maxLengthBetweenEqualCharacters(String s) {List<Pair> v = new ArrayList<Pair>();for (int i = 0; i < s.length(); i++) {v.add(new Pair(s.charAt(i), i));}Collections.sort(v);int i = 0;int ans = -1;int n = s.length();while (i < n) {int j = i;while (i + 1 < n && v.get(i).getFirst() == v.get(i + 1).getFirst())i++;if (i == n)break;ans = Math.max(ans, v.get(i).getSecond() - v.get(j).getSecond() - 1);i++;}return ans;}static class Pair implements Comparable<Pair> {private char first;private int second;public Pair(char first, int second) {super();this.first = first;this.second = second;}public char getFirst() {return first;}public void setFirst(char first) {this.first = first;}public int getSecond() {return second;}public void setSecond(int second) {this.second = second;}@Overridepublic int compareTo(Pair o) {return this.first - o.getFirst();}}}
C++
#include <bits/stdc++.h>using namespace std;int maxLengthBetweenEqualCharacters(string s){vector<pair<char, int>> v;for (int i = 0; i < s.size(); i++)v.push_back({s[i], i});sort(v.begin(), v.end());int i = 0;int ans = -1;int n = s.size();while (i < n){int j = i;while (i + 1 < n && v[i].first == v[i + 1].first)i++;if (i == n)break;ans = max(ans, v[i].second - v[j].second - 1);i++;}return ans;}int main(){string str = "abca";cout << maxLengthBetweenEqualCharacters(str);return 0;}
No comments:
Post a Comment