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