You are viewing a single comment's thread. Return to all comments →
quite clean C# solution with a lot of LINQ
public static int alternate(string s) { var dict = Enumerable.Range(0, 26) .ToDictionary(i => i, _ => new List<int>()); for (var i = 0; i < s.Length; i++) dict[s[i] - 'a'].Add(i); var positions = dict.Values .Where(p => p.Count > 0) .OrderByDescending(p => p.Count) .ThenBy(p => p[0]) .ToList(); var max = 0; for (var i = 0; i < positions.Count - 1; i++) { var list1 = positions[i]; if (list1.Count * 2 <= max) break; for (var j = i + 1; j < positions.Count; j++) { var list2 = positions[j]; if (list1.Count - list2.Count > 1) break; var alt1 = list1.Zip(list2, (p1, p2) => p1 - p2).All(x => x < 0); var alt2 = list1.Skip(1).Zip(list2, (p1, p2) => p1 - p2).All(x => x > 0); if (alt1 && alt2) max = Math.Max(max, list1.Count + list2.Count); } } return max; }
Seems like cookies are disabled on this browser, please enable them to open this website
Two Characters
You are viewing a single comment's thread. Return to all comments →
quite clean C# solution with a lot of LINQ