Python, LintCode, 13. Implement strStr()

class Solution:
    """
    @param: source: source string to be scanned.
    @param: target: target string containing the sequence of characters to match
    @return: a index to the first occurrence of target in source, or -1  if target is not part of source.
    """
    def strStr(self, source, target):
        # write your code here
        if source == None or target == None:
            return -1
        M = len(source)
        N = len(target)
        ptr_s = 0
        ptr_t = 0
        while ptr_s < M and ptr_t < N:
            if source[ptr_s] == target[ptr_t]:
                ptr_s += 1
                ptr_t += 1
            elif ptr_t == 0:
                ptr_s += 1
            else:
                ptr_t = 0       
        if ptr_t == N:
            return ptr_s - N
        else:
            return -1

猜你喜欢

转载自blog.csdn.net/u010342040/article/details/80337836