"a-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:15:07 26 4
gpt4 key购买 nike

我已经尝试这个问题很长时间了,但还没有走得太远。问题是要求生成一个字符串,其中输入字符串中的所有重复字符都被该字符的单个实例替换。

例如,

(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)))

但这似乎不对。请帮我修改它以使其工作。

谢谢!!

最佳答案

字符串使用起来有点烦人,所以我们将它包装在一个处理列表的工作函数中。这样我们就可以避免到处乱搞转换。

(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))]))

关于string - 从方案中的字符串中删除重复的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com