Imports System
Imports System.Collections.Generic
Public Class Program
Public Shared Function CountSubstringWithKDistinctChars(ByVal s As String, ByVal k As Integer) As Integer
Dim count As Integer = 0
For i As Integer = 0 To s.Length - 1
Dim ch As Char = s(i)
Dim tmp As String = "" & ch
Dim _set As ISet(Of Char) = New HashSet(Of Char)()
_set.Add(ch)
For j As Integer = i + 1 To s.Length - 1
Dim next_ch As Char = s(j)
_set.Add(next_ch)
tmp += next_ch
If tmp.Length >= k AndAlso _set.Count = k Then
count += 1
End If
Next
Next
Return count
End Function
Public Shared Sub Main(ByVal args As String())
Dim str As String = "characters"
Dim k As Integer = 4
Console.Write("Number of substrings with exactly k distinct characters = ")
Console.Write(CountSubstringWithKDistinctChars(str, k))
End Sub
End Class
' run:
'
' Number of substrings with exactly k distinct characters = 9
'