Find all the Cool Strings

In a given string. if all characters present in the string only appear once, then that string is considered cool. Given a string s find and return the number of cool substrings of length four found in s.


Note that if the same substring occurs multiple times, every time it appears should be added to the total number of cool substrings. A substring is a contiguous sequence of characters in a string.


Example: Input: s = “abcdcfc” Output: 1 Explanation: There are 4 substrings of length 4: “abcd”, “bcdc”, “cdcf”, and “dcfc”. The only cool substring of length 4 is “abcd”.


Constraints: • 1 <= s.length <= 100 • s consists of lowercase English letters.

using System;
using System.Collections.Generic;

public class HelloWorld
{


public static void Main(string[] args)
{
Console.WriteLine (CountCoolSubstrings(“abcdcfc”));
}

public static int CountCoolSubstrings(string s) {
int count = 0;
HashSet coolSubstrings = new HashSet();
for (int i = 0; i <= s.Length – 4; i++) { string substring = s.Substring(i, 4); if (IsCool(substring)) { if (!coolSubstrings.Contains(substring)) { coolSubstrings.Add(substring); } count++; } } return coolSubstrings.Count; }

public static bool IsCool(string s) { HashSet seenChars = new HashSet();
foreach (char c in s) {
if (seenChars.Contains(c)) {
return false;
}
seenChars.Add(c);
}
return true;
}


}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *