问题如下:
- 使用累积递归
- 函数消耗一个字符串并产生一个新字符串
- 连续出现的每个字符被替换为字母及其连续出现的次数
- 示例:“hellooo”=>“hel2o3”
- 问题是基于大学水平的
我尝试了以下方法:
(define (abbreviate str)
(local [(define str-lst (string->list str))
(define (count-duplicate lst char count)
(cond
[(empty? lst) count]
[(equal? (first lst) char)
(count-duplicate (rest lst)
(first lst)
(add1 count))]
[else (count-duplicate (rest lst)
(first lst)
count)]))
(define (build-string lst)
(cond
[(empty? lst) empty]
[else (cons (first lst)
(cons (string->list (number->string
(count-duplicate (rest lst)
(first lst) 1)))
(build-string (rest lst))))]))]
(build-string str-lst)))
但我得到了结果:
(list #\h (list #\4) #\e (list #\4) #\l (list #\4) #\l (list #\3) #\o (list #\3) #\o (列表#\2) #\o (列表#\1))
有什么帮助吗?