How to print the number of substrings with exactly k distinct characters in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class Program
    Public Shared Sub PrintSubstringWithKDistinctChars(ByVal s As String, ByVal k As Integer)
        Dim list As IList(Of String) = New List(Of String)()

        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
                    list.Add(tmp)
                End If
            Next
        Next

        Console.WriteLine(String.Join(", ", list))
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim str As String = "characters"
        Dim k As Integer = 4
				
        PrintSubstringWithKDistinctChars(str, k)
    End Sub
End Class




' run:
'
' char, chara, charac, harac, aract, ract, acte, cter, ters
'
'		
		
		

 



answered Sep 17, 2022 by avibootz
...