我不知道该怎么做。 这是场景。我需要计算要删除的次数,以便字符串中没有任何连续的字符。例如
AAABBBCCC = 6个缺失。 2 on c,2 on b,2 on a使其不连续。
感谢您的帮助。我正在用VB.Net写作。
答案 0 :(得分:3)
此方法适用于任何类型:
Shared Function CountConsecutiveDuplicates(Of T)(input As IEnumerable(Of T)) As Int32
Dim count As Int32 = 0
Dim comparer = EqualityComparer(Of T).Default
' optimization for lists and arrays: '
Dim listT = TryCast(input, IList(Of T))
If listT IsNot Nothing Then
If listT.Count <= 1 Then Return 0
For i As Int32 = 0 To listT.Count - 2
If comparer.Equals(listT(i), listT(i + 1)) Then
count += 1
End If
Next
Return count
End If
If Not input.Any() Then Return 0
Dim this As T = input.First()
For Each item As T In input.Skip(1)
If comparer.Equals(this, item) Then
count += 1
End If
this = item
Next
Return count
End Function
用法:
Dim numDeletes = CountConsecutiveDuplicates("AAABBBCCC") ' 6
你可以把它变成一个扩展方法:
Module GeneralExtensions
<Extension()>
Function CountConsecutiveDuplicates(Of T)(input As IEnumerable(Of T)) As Int32
Dim count As Int32 = 0
Dim comparer = EqualityComparer(Of T).Default
' optimization for lists and arrays: '
Dim listT = TryCast(input, IList(Of T))
If listT IsNot Nothing Then
If listT.Count <= 1 Then Return 0
For i As Int32 = 0 To listT.Count - 2
If comparer.Equals(listT(i), listT(i + 1)) Then
count += 1
End If
Next
Return count
End If
If Not input.Any() Then Return 0
Dim this As T = input.First()
For Each item As T In input.Skip(1)
If comparer.Equals(this, item) Then
count += 1
End If
this = item
Next
Return count
End Function
End Module
然后你甚至可以这样使用它:
Dim numDeletes = "AAABBBCCC".CountConsecutiveDuplicates()
答案 1 :(得分:0)
Public Module Tester
Public Sub Main()
Dim _inStr As String = "AAABBBBCCCCC"
Dim _reduced As Char() = _inStr.ToCharArray.Distinct().ToArray
Console.WriteLine("{0} >> {1}", _inStr, New String(_reduced))
For Each _c As Char In _reduced
Console.WriteLine("Char: {0} remove: {1}", _c, _inStr.Where(Function(x) x = _c).Count - 1)
Next
Console.ReadKey()
End Sub
End Module
输出:
AAABBBBCCCCC >> ABC
Char: A remove: 2
Char: B remove: 3
Char: C remove: 4
答案 2 :(得分:0)
我不明白你想要如何计算删除量或者你打算如何处理结果,但简单地删除所有连续字符的简单解决方案可能如下所示:
Dim str as String = "AAABBBCCC"
For Each ch As Char In str
str = str.Replace(ch, "")
str = str & ch
Next
这将简单地返回&#34; ABC&#34;。如果需要,您可以随时添加一些变量和/或输出来计算每个字符的删除。
答案 3 :(得分:0)
我认为你需要这样的东西,
Dim myString As String = "AAAABBCCCDDDDD"
Dim toDelete As List(Of Integer) = Nothing
Dim intLoopIndex As Integer = 0
Dim i As Integer
For i = 0 To myString.Length - 1
Do While myString(i).ToString = myString(i + 1).ToString
toDelete.Add(i + 1)
Loop
Next
Debug.WriteLine("You must delelte in total : " & toDelete.Count.ToString & " character(s)")
For k = 0 To toDelete.Count - 1
Debug.Write("Must delete the character from your string at position : " & toDelete(k).ToString)
Next
试试吧!并玩:)