13. Implement strStr()

實現

  1. 從 0 到 source_length - target_length + 1 開始遍歷
  2. 再從 0 到 target_length 進行遍歷,逐個去比較,如果不相等就比下一次

代碼

class Solution:
    """
    @param source:
    @param target:
    @return: return the index
    """
    def strStr(self, source, target):
        if source is None or target is None:
            return -1

        source_length = len(source)
        target_length = len(target)

        for i in range(source_length - target_length + 1):
            j = 0

            while j < target_length:
                if source[i + j] != target[j]:
                    break
                j += 1

            if j == target_length:
                return i

        return -1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章