代码之家  ›  专栏  ›  技术社区  ›  meallhour

在另一个字符串中查找字符串的出现

  •  -2
  • meallhour  · 技术社区  · 3 年前

    细节:

    • 有两条线 x y .

    • 计算的数量 occurrence of y in x 如下所示:

      • y的长度是3。

      • y == x[i] x[i+2] x[i+4]


    实例

    x = "aabbcc"
    y = "abc" 
    output: 2
    

    我的代码:

    def solution(x, y):
        i, count = 0, 0
        j = i + 2
        k = i + 4
        
        while i+4 < len(x):
            cur = x[i]
            while i < len(x) and i != j:
                i += 1
            while i < len(x) and i != k:
                i += 1
            count += 1
            
        return count
        
    solution(x, y)
                
    

    我得到了 count = 1 。它应该给予 count = 2


    3 回复  |  直到 3 年前
        1
  •  1
  •   Grismar    3 年前

    您的代码中有几个逻辑错误。

    问题发生在这里:

            while i < len(x) and i != j:
                i += 1
            res.append(x[i])
    

    你一直在增加 i 直到要么 len(x) 或更大,或者直到它与 j 。但是自从你开始 j 成为 2 在开始时(并且从不更新它),它将简单地以设置结束 len(x) x[i] 将因此失败,因为 x[len(x)] 尝试对外部的元素进行索引 x .

    然而,还有几点要说:

    • 你收集你在里面发现的东西 res ,但确实只想要一个数字(例如。 2. 因此
    • 您定义 count 但不要用它
    • 在三个独立的变量中跟踪字符串中的坐标( , j , k )有很多逻辑来增加第一个,但实际上你所需要的只是一次一个位置地遍历字符串,并直接查看偏移

    考虑到所有这些和问题描述,你可能会选择这样的东西:

    x = "aabbcc"
    y = "abc"
    
    
    def solution(x, y):
        i, count = 0, 0
    
        while i + 4 < len(x):
            if (x[i], x[i+2], x[i+4]) == (y[0], y[1], y[2]):
                count += 1
            i += 1
    
        return count
    
    
    print(solution(x, y))
    

    然而,Python有一些聪明之处,这将使它变得更简单(或至少更短):

    def solution(x, y):
        count = 0
    
        for i in range(len(x)-4):
            if x[i:i+5:2] == y:  # slicing with a stride of two, instead of direct indexing
                count += 1
    
        return count
    

    甚至:

    def solution(x, y):
        return len([x for i in range(len(x)-4) if x[i:i+5:2] == y])
    

    但我觉得这有点过于强调简洁而非可读性了。

        2
  •  1
  •   Nick SamSmith1986    3 年前

    生成器表达式解决方案,利用 True/False == 1/0 在数字上下文中:

    def solution(x, y):
        return sum(y == x[i:i+5:2] for i in range(len(x)-4))
    
        3
  •  0
  •   Karl Knechtel    3 年前

    当y==x[i]x[i+2]x[i+4]时,增加“计数”值

    这与简单地创建由以下组成的字符串相同 x[0], x[2], x[4]... (每个偶数字符)和由以下组成的字符串 x[1], x[3], x[5]... (每个奇数字符);计数的出现次数 y 在每个;并将这两个结果相加。

    创建字符串是琐碎的 common duplicate 。计算子字符串的出现次数为 also well-trodden ground .将这些工具放在一起:

    def spread_substrings(needle, haystack):
        even_haystack = haystack[::2]
        odd_haystack = haystack[1::2]
        return even_haystack.count(needle) + odd_haystack.count(needle)
    
    推荐文章