반응형
    
    
    
  https://leetcode.com/problems/largest-substring-between-two-equal-characters/
📕 풀이방법
📔 입력 및 초기화
1. alphabat별 index를 저장할 map 변수 alphaIndexMap을 선언해 줍니다.
2. 정답 변수 ans를 선언 후 -1로 초기화합니다.
📔 풀이과정
s에 대해 for loop를 수행합니다.
1. 한 번이라도 나온 적 있는 alphabat이라면 두 문자의 거리는 i - 해당index - 1이므로 ans와 거리 값 중 최댓값을 저장해줍니다.
2. 한 번도 나온 적 없다면 최초의 alphabat의 index를 저장해줍니다.
📔 정답 출력 | 반환
ans를 반환합니다.
📕 Code
📔 C++
class Solution {
public:
    int maxLengthBetweenEqualCharacters(string s) {
        map <char,int> alphaIndexMap;
        int ans = -1;
        for(int i = 0; i < s.size(); i++) {
            char c = s[i];
            if(alphaIndexMap.count(c)) {
                ans = max(ans, i - alphaIndexMap[c] - 1);
            } else {
                alphaIndexMap[c] = i;
            }
        }
        return ans;
    }
};*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > 자료구조' 카테고리의 다른 글
| (C++) - LeetCode (easy) 1700. Number of Students Unable to Eat Lunch (0) | 2024.06.16 | 
|---|---|
| (C++) - LeetCode (easy) 1656. Design an Ordered Stream (0) | 2024.05.25 | 
| (C++) - LeetCode (easy) 1614. Maximum Nesting Depth of the Parentheses (0) | 2024.05.11 | 
| (C++) - LeetCode (easy) 1544. Make The String Great (0) | 2024.04.23 | 
| (C++) - LeetCode (easy) 1528. Shuffle String (0) | 2024.04.21 |