[Leetcode] [Python]28:implement strStr ()

Source: Internet
Author: User

#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '

28:implement StrStr ()
https://oj.leetcode.com/problems/implement-strstr/

Implement strStr ().
Returns the index of the first occurrence of needle in haystack, or-1 if needle are not part of haystack.

===comments by dabay===
Finding substrings in long strings is, of course, the KMP algorithm. Since it's a three-person algorithm, it's definitely not easy. Let's study it when you are empty.
Here is the intuitive solution, traversing the long string, the beginning and the short string of a character to compare, if all are compared, the explanation found.
If the traversal is over, there is no return, the description is not found, return-1.
‘‘‘

Class Solution:
# @param haystack, a string
# @param needle, a string
# @return An integer
def strStr (self, haystack, needle):
i = 0
While I < Len (haystack)-Len (needle) + 1:
M,n = i,0
While n < len (needle) and haystack[m] = = Needle[n]:
M + = 1
n + = 1
if n = = Len (needle):
return I
i + = 1
Else
Return-1


def main ():
Sol = solution ()
Haystack = "Ahi"
needle = "HI"
Print sol.strstr (haystack, needle)


if __name__ = = "__main__":
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)

[Leetcode] [Python]28:implement strStr ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.