Programming Camp – Algorithm Training Camp – Day 9

1. Repeated Substring Pattern (Leetcode Number: 459)

General Solution

Put the "candidate" substring in the sliding window and move it till the end of the string

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:

        fast = 0
        ifexist = 0
        
        # Find the possible substring by comparing the value of an element with the first element.
        while fast <= len(s) // 2 and len(s) != 1:

            if s[fast] == s[0]:

                win_width = fast
                
                # When the length of the input list is 1, it's a corner case that needs to be verified separately
                if win_width == 0:
                    for i in range(len(s)):
                        if s[i] == s[0]:
                            ifexist = 1
                        else:
                            ifexist = 0
                            break
                    if ifexist == 1:
                        return True
                    fast  += 1
                    continue
                else:
                    num_win = len(s) // win_width
                
                n = 1
                
                # Check if the current "qualified" string is the substring that can construct the whole string
 
                while n < num_win:
                    if s[: fast] == s[n * win_width : fast + n * win_width] and len(s) % win_width == 0:
                        ifexist = 1
                    else:
                        ifexist = 0
                        break
                    n += 1    
                    
            if ifexist == 1:
                return True
            else:
                fast += 1

2. Find the Index of the First Occurrence in a String (Leetcode Number: 28)

General Solution

Same with Q1

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:

        ifexist = 0
        n_len = len(needle)
        h_len = len(haystack)
        
        p_str = ""
        
        for index_h in range(h_len - n_len + 1):
            if haystack[index_h] == needle[0]:
                index_temp = index_h
                for index_n in range(n_len):
                    if haystack[index_temp] == needle[index_n]:
                        ifexist = 1
                        index_temp += 1
                    else:
                        ifexist = 0
                        break
                if ifexist == 1:
                    return index_h
                else:
                    continue
            else:
                continue
        if ifexist == 0:
            return -1
        

                
                    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值