"""https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_searchthis algorithm tries to find the pattern from every position ofthe mainString if pattern is found from position i it add it tothe answer and does the same for position i+1Complexity : O(n*m)n=length of main stringm=length of pattern string"""def naive_pattern_search(s: str, pattern: str) -> list:""">>> naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")[4, 10, 18]>>> naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")[]>>> naive_pattern_search("", "ABC")[]>>> naive_pattern_search("TEST", "TEST")[0]>>> naive_pattern_search("ABCDEGFTEST", "TEST")[7]"""pat_len = len(pattern)position = []for i in range(len(s) - pat_len + 1):match_found = Truefor j in range(pat_len):if s[i + j] != pattern[j]:match_found = Falsebreakif match_found:position.append(i)return positionif __name__ == "__main__":assert naive_pattern_search("ABCDEFG", "DE") == [3]print(f"{naive_pattern_search('ABAAABCDBBABCDDEBCABC', 'ABC') = }")
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。