从方案中的字符串中删除重复的字符

时间:2011-05-29 17:24:43

标签: string recursion scheme

我一直在尝试这个问题很长一段时间但是我没有做得很远。问题是要求生成一个字符串,其中来自输入字符串的所有重复字符都被该字符的单个实例替换。

例如,

(remove-repeats "aaaab") => "ab"
(remove-repeats "caaabb aa") => "cab a"

由于我试图使用累积递归来做到这一点,到目前为止我有:

(define (remove-repeats s) 
  (local
    [(define (remove-repeats-acc s1 removed-so-far)
      (cond
        [(empty? (string->list s1))""]
        [else 
         (cond
           [(equal? (first (string->list s1)) (second (string->list s1))) 
         (list->string (remove-repeats-acc (remove (second (string->list s1)) (string->list s1)) (add1 removed-so-far)))]
           [else (list->string (remove-repeats-acc (rest (string->list s1)) removed-so-far))])]))]
    (remove-repeats-acc s 0)))

但这似乎不对。请帮我修改一下。

谢谢!!

2 个答案:

答案 0 :(得分:4)

使用字符串有点烦人,所以我们将它包装在一个处理列表的工作函数中。通过这种方式,我们可以避免乱搞各地的转化。

(define (remove-repeats str)
  (list->string (remove-repeats/list (string->list str))))

现在我们可以使用简单的递归来定义remove-repeats / list函数:

(define (remove-repeats/list xs)
  (cond
    [(empty? xs) xs]
    [(empty? (cdr xs)) xs]
    [(equal? (car xs) (cadr xs)) (remove-repeats/list (cdr xs))]
    [else (cons (car xs) (remove-repeats/list (cdr xs)))]))

这不是尾递归,但现在添加累加器应该更容易:

(define (remove-repeats str)
  (list->string (remove-repeats/list-acc (string->list str) '())))

(define (remove-repeats/list-acc xs acc)
  (cond
    [(empty? xs) (reverse acc)]
    [(empty? (cdr xs)) (reverse (cons (car xs) acc))]
    [(equal? (car xs) (cadr xs)) (remove-repeats/list-acc (cdr xs) acc)]
    [else (remove-repeats/list-acc (cdr xs) (cons (car xs) acc))]))

答案 1 :(得分:1)

这是我喜欢的版本,Typed Racket

#lang typed/racket
(: remove-repeats : String -> String)
(define (remove-repeats s)
  (define-values (chars last)
    (for/fold: ([chars : (Listof Char) null] [last : (Option Char) #f])
      ([c (in-string s)] #:when (not (eqv? last c)))
      (values (cons c chars) c)))
  (list->string (reverse chars)))