【问题标题】:For which scenarios my solution to this puzzle fails在哪些情况下,我对这个难题的解决方案失败了
【发布时间】:2012-05-05 04:10:37
【问题描述】:

对于如下框架的问题拼图

对于两个字符串 A 和 B,我们将字符串的相似度定义为两个字符串共有的最长前缀的长度。例如,字符串“abc”和“abd”的相似度为2,而字符串“aaa”和“aaab”的相似度为3。 计算字符串 S 与其每个后缀的相似度总和。

我编写了以下解决方案,它只能通过三个测试用例,但我无法找出它失败的测试用例,你能帮我找出它失败的场景吗。

示例输入: 2 阿巴巴 啊

示例输出: 11 3

说明: 对于第一种情况,字符串的后缀是“ababaa”、“babaa”、“abaa”、“baa”、“aa”和“a”。这些字符串中的每一个与字符串“ababaa”的相似度分别为 6,0,3,0,1,1。因此答案是 6 + 0 + 3 + 0 + 1 + 1 = 11。

对于第二种情况,答案是 2 + 1 = 3。

 def find_suffix(string):
        if len(string) == 0:
            return 0
        tail = 0
        head = 1
        occurences = [1]
        while head < len(string):
            if string[head] == string[tail]:
                occured = occurences[tail] + 1
                tail = tail + 1
            else:
                if string[0] == string[head]:
                    occured = 2
                    tail = 1
                else:
                    occured = 1
                    tail = 0

            occurences.append(occured)
            head = head + 1
        return sum(occurences)

【问题讨论】:

  • "对于两个字符串..." - 两个字符串在哪里?
  • @KarolyHorvath 抱歉,我忘记添加行计算字符串 S 与每个后缀的相似性总和。现在添加。
  • 有哪些测试用例,哪些失败了?
  • 我无法访问测试用例,但它只能通过 3 个测试用例 10
  • @DaClown: 随机无关链接?

标签: algorithm puzzle testcase


【解决方案1】:

我不知道蟒蛇。我用方案语言编写了这段代码。它适用于 DrRacket

(define inp-string (read))

(define inp-list (string->list inp-string))

(define (sim-len l1 l2)
  (cond ((or (null? l1) (null? l2)) 0)
        ((char=? (car l1) (car l2)) (+ 1 (sim-len (cdr l1) (cdr l2))))
        (else
          0)))

(define inp-strlen (string-length inp-string))

(define iter-cnt 0)
(define final-ans 0)

(define (sum-of-sim l)
 (define (iter count)
   (cond ((null? l) 0)
         ((= iter-cnt inp-strlen) 0)
         (else
         (set! final-ans (+ final-ans 
         (sim-len inp-list (string->list (substring inp-string iter-cnt inp-strlen)))))
           (set! iter-cnt (+ iter-cnt 1))
    (iter iter-cnt))))
(iter iter-cnt))

(sum-of-sim inp-list)

final-ans

我测试的案例如下:

输入:- "" final-ans =0,输入:- "r" final-ans =1,输入:- "rajesh" final-ans =6,输入:- "rajesh bhat" final-ans=11 , 输入:- "rajraj" final-ans =9, 输入:- "aaaaaa" final-ans =21

其他情况是什么?希望这可以帮助。

【讨论】:

  • 我的解决方案也通过了所有这些测试用例,所以仍然无法弄清楚它在哪些场景下失败了。
猜你喜欢
  • 2022-12-04
  • 2020-08-09
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2019-11-25
  • 2022-01-15
  • 2012-03-20
相关资源
最近更新 更多