Positions of Large Groups, by LeetCode
Hi folks, long time no see! Problem is here: https://leetcode.com/problems/positions-of-large-groups/description/:
public class Solution
{
public IList<IList<int>> LargeGroupPositions(string S)
{
List<IList<int>> retVal = new List<IList<int>>();
int previousIndex = 0;
for (int i = 1; i < S.Length; i++)
{
if (S[i] != S[previousIndex])
{
if (i - previousIndex >= 3)
{
List<int> list = new List<int>();
list.Add(previousIndex);
list.Add(i - 1);
retVal.Add(list);
}
previousIndex = i;
}
else if (i == S.Length - 1 && S[i] == S[previousIndex] && i - previousIndex + 1 >= 3)
{
List<int> list = new List<int>();
list.Add(previousIndex);
list.Add(i);
retVal.Add(list);
}
}
return retVal;
}
}
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 "yy"
.
Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
The final answer should be in lexicographic order.
The solution is straightforward: index manipulation, understanding some of the data structures of your favorite language (in my case C#), linear pass keeping track of the beginning of the current block (in the code below expressed by "previousIndex"), and that's pretty much it! Have fun, code is below, many hugs!!! Marcelopublic class Solution
{
public IList<IList<int>> LargeGroupPositions(string S)
{
List<IList<int>> retVal = new List<IList<int>>();
int previousIndex = 0;
for (int i = 1; i < S.Length; i++)
{
if (S[i] != S[previousIndex])
{
if (i - previousIndex >= 3)
{
List<int> list = new List<int>();
list.Add(previousIndex);
list.Add(i - 1);
retVal.Add(list);
}
previousIndex = i;
}
else if (i == S.Length - 1 && S[i] == S[previousIndex] && i - previousIndex + 1 >= 3)
{
List<int> list = new List<int>();
list.Add(previousIndex);
list.Add(i);
retVal.Add(list);
}
}
return retVal;
}
}
3 liner :)
ReplyDeleteclass Solution {
public:
vector> largeGroupPositions(const string& S) {
vector> groups;
for (int start = 0, end = 1; end < S.size(); start = end, ++end) {
while (S[end] == S[end-1]) end += 1;
if (end - start >= 3) groups.push_back({start, end-1});
}
return groups;
}
};