美文网首页
[easy][String][Two-pointer]28. I

[easy][String][Two-pointer]28. I

作者: 小双2510 | 来源:发表于2017-11-27 11:56 被阅读0次

    原题是:

    Implement

    strStr().

    Return the index of the first occurrence of needle in haystack, or

    -1

    if needle is not part of haystack.

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1

    思路是:

    从一个string中找另一个子string的位置,用两个指针,一个指着第一个相同元素的位置,第二个去检查后序的元素是否依次相同。
    这个题,我在写代码的过程中,要十分注意i,j的变化。
    while训话一定要记得更新循环变量。
    还有while,if-else嵌套时,一定要想清楚逻辑。

    代码是:

    class Solution:
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            if not needle:
                return 0
            if not haystack:
                return -1
            
            i= 0
            lenhaystack = len(haystack)
            lenneedle = len(needle)
            
            while i < lenhaystack - lenneedle + 1 : 
                if haystack[i] == needle[0]:
                    j = 1
                    while j < lenneedle :
                        if haystack[i + j] != needle[j]:
                            break
                        else:
                            j += 1
                    if j == lenneedle:
                        #print(j)
                        #print(i)
                        return i
                i += 1
        
            return -1
    

    因为python的特性,别人的一个很好的代码:

    class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        for i in range(len(haystack) - len(needle)+1):
            if haystack[i:i+len(needle)] == needle:
                return i
        return -1
    

    相关文章

      网友评论

          本文标题:[easy][String][Two-pointer]28. I

          本文链接:https://www.haomeiwen.com/subject/ppwrbxtx.html