c# + longest streak in strings code example
Example: c# + longest streak in strings
public static void Main(string[] args)
{
Console.WriteLine(Streak("aaabbCCC88ddddacC8"));
}
public static int Streak(string s)
{
int max = 0;
int count = 0;
for (int i = 1; i < s.Length; i++)
{
char currentLetter = s[i];
char previousLetter = s[i - 1];
if (currentLetter == previousLetter) count++;
if (count > max) max = count +1;
if (currentLetter != previousLetter) count = 0;
}
return max;
}
---------------------------------------------------Option 1
public static int Streak(string s)
{
int max = 0;
for (int i = 0; i < s.Length; i++)
{
int count = 0;
for (int j = i; j < s.Length; j++)
{
if (s[i] == s[j]) count++;
if (count > max) max = count;
if (s[i] != s[j]) break;
}
}
return max;
}
-----------------------------------------------------option 2
public static string Streak(string s)
{
Dictionary<char, int> dict = new Dictionary<char, int>();
for (int i = 1; i < s.Length; i++)
{
char currentLetter = s[i];
char previousLetter = s[i - 1];
if (currentLetter == previousLetter)
{
if (dict.ContainsKey(currentLetter))
dict[currentLetter] = dict[currentLetter] + 1;
else if (!dict.ContainsKey(currentLetter))
{
dict.Add(currentLetter, 2);
}
}
}
var ordered = dict.OrderByDescending(dict => dict.Value)
.ToDictionary(dict => dict.Key, dict => dict.Value);
var result = ordered.Take(3).ToDictionary(d => d.Key, d => d.Value);
var resultToString = string.Join(Environment.NewLine, result);
return resultToString;
}
-----------------------------------------------------option 3