有两种方法可以回答这个问题。
第一种是简单的行程编码方案,其中输入cabc
结果为c1 a1 b1 c1
. 这样做的好处是,您通常可以以相当低的内存要求立即输出内容来启动:
input-string := Get-Input
(* nil is the representation of no characters here. *)
last-char := nil
count := 0
For Each (char c) In input-string
If c = last-char Then
count := count + 1
Else
If last-char = nil Then
count := 1
last-char := c
Else
Display last-char, count
count := 1
last-char := c
End If
End If
Loop
If count != 0 Then
Display last-char, count
End If
我设想的另一个解决方案将保留顺序并确定字符串中所有唯一字母的计数,c2 a1 b1
产生cabc
. 这个解决方案有点复杂,需要更多的内存和更多的执行时间,但由于缺少重复的字母,它会导致更紧凑的输出:
input-string := Get-Input
(* 26 is the number of letters a-z. *)
counts := Create-Array 26
order-string := ""
For Each (char c) In input-string
i := Locate-Char order-string, c
If i = 0 Then
order-string := order-string + c
counts [Length order-string] := 1
Else
counts [i] := counts [i] + 1
End If
Loop
For i := 1 To (Length order-string)
Display (Char-At order-string, i), counts [i]
Loop
第一个应该可以直接转换为 QBASIC,但您可能需要使用帮助文件来了解DIM
关键字以及如何使用它来创建数组。该算法假设数组从 1 开始,而不是 0。