String 不使用反转检测回文
我在想一种方法来创建一个函数,它可以检测回文而不使用反向。。。 我想我会很聪明,做一个条件,子串0到中间等于子串end到中间。我我发现它只适用于3个字母“哇”的单词,因为“w”=“w”。但是如果字母像“呜呜”,wo并不等于“呜呜”。不使用反向函数检测回文的方法是什么 提示或解决方案可能非常有用String 不使用反转检测回文,string,scheme,racket,reverse,palindrome,String,Scheme,Racket,Reverse,Palindrome,我在想一种方法来创建一个函数,它可以检测回文而不使用反向。。。 我想我会很聪明,做一个条件,子串0到中间等于子串end到中间。我我发现它只适用于3个字母“哇”的单词,因为“w”=“w”。但是如果字母像“呜呜”,wo并不等于“呜呜”。不使用反向函数检测回文的方法是什么 提示或解决方案可能非常有用 (define (palindrome? str) (cond ((equal? (substring str 0 (- (/ (string-length str) 2) 0.5))
(define (palindrome? str)
(cond
((equal? (substring str 0 (- (/ (string-length str) 2) 0.5))
(substring str (+ (/ (string-length str) 2) 0.5) (string-length str))) str)
(else false)))
哦,我使用的是初学者语言,所以我不能使用地图或过滤器之类的东西
是的,我知道这是一个非常无用的函数哈哈简单
i
,从0到floor(length/2)
,比较索引i
和索引length-i-1
处的字符(define (palindrome? str)
(define len (string-length str))
(define halfway <???>)
(let loop ((i 0))
(cond ((>= i halfway) #t)
((char=? <???> <???>)
(loop (+ i 1)))
(else #f))))
(定义(回文?str)
(定义len(字符串长度str))
(定义一半)
(let循环((i0))
(cond((>=i中途)#t)
((字符=?)
(循环(+i 1)))
(其他#f))
解决这个问题的方法是在给定的索引中乱用字符串的字符。诀窍是明智地使用。在这里,让我给你一些提示,指出一个适用于初学者语言的解决方案:
; this is the main procedure
(define (palindrome? s)
; it uses `loop` as a helper
(loop <???> <???> <???>))
; loop receives as parameters:
; `s` : the string
; `i` : the current index, starting at 0
; `n` : the string's length
(define (loop s i n)
(cond (<???> ; if `i` equals `n`
<???>) ; then `s` is a palindrome
(<???> ; if the char at the current index != its opposite (*)
<???>) ; then `s` is NOT a palindrome
(else ; otherwise
(loop <???> <???> <???>)))) ; advance the recursion over `i`
这里有一个创造性的答案
(define (palindrome list)
(let halving ((last list) (fast list) (half '()))
(cond ((null? fast) (equal? half last))
((null? (cdr fast)) (equal? half (cdr last)))
(else (halving (cdr last) (cddr fast)
(cons (car last) half))))))
它沿着列表的一半移动(使用
fast
找到结尾),建立一个前half
的列表,然后简单地使用equal?
上的half
与列表的其余部分一起使用。我不知道您的语言或关于它的任何功能。但是,如果你有一些东西,可以索引的字母或单词与一个变量和循环它。因此,对于字符串前半部分中的每个字母,if string.index(字母)-string.index(-letter)。因此,第一个字母=从结尾开始的第一个字母,第二个字母=从结尾开始的第二个字母,依此类推,直到你到达中间。尽管你必须添加一些东西来处理偶数和奇数长度的单词。这就是我所评论的。我无法验证代码,但逻辑是可靠的。呃,它说定义了loop或let?是因为我在使用drracket吗?@user2113651 Chris的解决方案使用了一个“命名let”,这在初学者的语言中是不可用的。有关如何使用适用于您语言的程序解决问题的提示,请参见我的答案。请传递s
(无修改)、i
(添加一个)和n
(无修改);这是主要的过程(定义(回文);它使用loop
作为助手(循环)),我喜欢它!虽然我会对变量重命名一点,比如用tortoise
和hare
代替last
和fast
。我本来打算用slow
和fast
的,但是我需要last
所以相等?
的比较有点可读。hare
和tortoise
是这类动物的传统名称活动
(define (palindrome list)
(let halving ((last list) (fast list) (half '()))
(cond ((null? fast) (equal? half last))
((null? (cdr fast)) (equal? half (cdr last)))
(else (halving (cdr last) (cddr fast)
(cons (car last) half))))))