在不使用反向的情况下检测回文

时间:2013-04-02 22:53:17

标签: string scheme racket reverse palindrome

我在想一种方法来创建一个不使用反向检测回文的函数... 我以为我会很聪明,做一个子串0到中等于子串到中间的条件。我发现它只适用于带有3个字母的单词“哇”,因为“w”=“w”。但如果这些字母就像是“哇哇”,那么我就不等于ow。什么是在不使用反向功能的情况下检测回文?

提示或解决方案可能非常有用

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

哦,我正在使用初学者语言,因此我无法使用地图或过滤器等内容

是的,我知道这是一个非常无用的功能哈哈

3 个答案:

答案 0 :(得分:1)

通过弄乱给定索引中的字符串字符可以解决这个问题。诀窍是明智地使用string-ref。在这里,让我给你一些提示,指出一个可以与初学者语言一起使用的解决方案:

; 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`

当然,有趣的部分是标有(*)的部分。想想看,如果0索引处的char等于n-1索引处的char(n是字符串的长度),则字符串是回文 1索引处的char等于n-2索引处的char,依此类推。通常,如果i索引处的char等于所有n-i-1的{​​{1}}索引处的char(其“相反”),那么我们可以得出结论,该字符串是回文 - 但如果一对相对的字符彼此不相等,则它不是回文。

作为进一步优化,请注意您不需要遍历整个字符串,这足以测试字符串长度的一半(这在Chris的回答中有解释) ) - 直观地说,你可以看到如果i处的char等于i处的char,那么n-i-1处的char等于n-i-1处的char,所以没有必要两次执行相同的测试。

尝试自己编写程序,不要忘记测试它们:

i

答案 1 :(得分:1)

这是一个富有创意的答案

(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列表的其余部分。

答案 2 :(得分:0)

简单。

  1. 对于每个i,从0到floor(length / 2),比较索引i和索引length - i - 1处的字符。
  2. 如果不匹配,请返回false。
  3. 否则,如果循环用完,则返回true。
  4. 骨骼代码:

    (define (palindrome? str)
      (define len (string-length str))
      (define halfway <???>)
      (let loop ((i 0))
        (cond ((>= i halfway) #t)
              ((char=? <???> <???>)
               (loop (+ i 1)))
              (else #f))))