https://leetcode.com/problems/positions-of-large-groups/description/
Positions of Large Groups - LeetCode
Can you solve this real interview question? Positions of Large Groups - In a string s of lowercase letters, these letters form consecutive groups of the same character. For example, a string like s = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z", and
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 입력 및 초기화
정답 변수 vector<vector<int>> ans를 선언해줍니다. consecutive한 문자열의 시작과 끝 idx를 저장할 변수 startIdx, endIdx를 선언해줍니다.
📔 풀이과정
s문자열에 대해 for loop를 수행하며 다음을 수행합니다. 두 경우가 있습니다.
1. 현재 문자와 다음 문자가 다르다면
startId - endIdx가 연속적인 문자열의 길이기 때문이므로 2이상이라면 3개 이상이 됩니다. 따라서 이 경우에 ans에 범위를 push_back해줍니다.
2. 이외의 경우 오른쪽 범위가 1증가하므로 endIdx를 1증가시킵니다.
3. loop탈출 후 마지막 범위를 계산해서 ans에 push_back 여부를 결정해줍니다.
📕 Code
📔 C++
class Solution {
public:
vector<vector<int>> largeGroupPositions(string s) {
vector<vector<int>> ans;
int startIdx = 0, endIdx = 0;
for(int i = 0; i < s.size()-1; i++) {
if(s[i] != s[i+1]) {
if(endIdx - startIdx >= 2) {
ans.push_back({startIdx, endIdx});
}
startIdx = i+1, endIdx = i+1;
} else {
endIdx++;
}
}
if(endIdx - startIdx >= 2) {
ans.push_back({startIdx, endIdx});
}
return ans;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 836. Rectangle Overlap (0) | 2023.07.27 |
---|---|
(C++) - LeetCode (easy) 832. Flipping an Image (0) | 2023.07.26 |
(C++) - LeetCode (easy) 819. Most Common Word (0) | 2023.07.21 |
(C++) - LeetCode (easy) 806. Number of Lines To Write String (0) | 2023.07.17 |
(C++) - LeetCode (easy) 766. Toeplitz Matrix (0) | 2023.07.11 |