28. Implement strStr() [easy]

来源:互联网 发布:eclipse导入jar包源码 编辑:程序博客网 时间:2024/06/05 09:11

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Java

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


Python

class Solution(object):    def strStr(self, haystack, needle):        """        :type haystack: str        :type needle: str        :rtype: int        """        # try:        #     return haystack.index(needle)        # except:        #     return -1        for i in range(len(haystack)-len(needle)+1):             found=True            for j in range(len(needle)):                if haystack[i+j]!=needle[j]:                    found=False                    break            if found:                return i        return -1


0 0
原创粉丝点击