You are viewing a single comment's thread. Return to all comments →
Here is my C# version:
class Segment { public char Key { get; set; } public long Count { get; set; } } // Complete the SubstrCount function below. static long SubstrCount(int n, string s) { var count = 0L; List<Segment> segments = ToSegments(s); for (var i = 0; i < segments.Count; i++) count += GetCount(segments, i); return count; } private static List<Segment> ToSegments(string s) { List<Segment> segments = new List<Segment>(); var str = s + " "; var count = 1L; var ch = str[0]; for (int i = 1; i <= s.Length ; i++) { if(str[i].Equals(ch)) { count++; } else { segments.Add(new Segment { Key = ch, Count = count }); count = 1; ch = str[i]; } } return segments; } private static long GetCount(List<Segment> segments, int i) { return IsMid(segments, i) ? Math.Min(segments[i - 1].Count, segments[i + 1].Count) + 1 : SegmentToCount(segments[i]); } private static bool IsMid(List<Segment> segments, int i) { return i > 0 && i < segments.Count - 1 && segments[i].Count == 1 && segments[i - 1].Key == segments[i + 1].Key; } private static long SegmentToCount(Segment s) { return (s.Count * (s.Count + 1)) / 2; }
Seems like cookies are disabled on this browser, please enable them to open this website
Special String Again
You are viewing a single comment's thread. Return to all comments →
Here is my C# version: