leetcode 28 Implement strStr()

Java:

class Solution {
    public int strStr(String haystack, String needle) {
        for(int i=0;;i++){
            for(int j=0;;j++){
                if(j==needle.length()) return i;
                if(i+j==haystack.length()) return -1;
                if(needle.charAt(j)!=haystack.charAt(i+j)) break;
            }
        }
    }
}

Python:

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        i=0
        while(i<=len(haystack) - len(needle)):
            if needle == haystack[i:i+len(needle)]:
                return i
            i+=1
        return -1

猜你喜欢

转载自blog.csdn.net/mrxjh/article/details/79777243