卖萌的弱渣

I am stupid, I am hungry.

Implement strStr

Implement strStr().

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

Solution

(Implement-strStr.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle == haystack:
            return 0
        if needle == "":
            return 0
        i = 0
        while i < len(haystack)-len(needle)+1:
            j = 0
            tmp = i
            while i < len(haystack) and j < len(needle) and haystack[i] == needle[j]:
                i+=1
                j+=1
            if j == len(needle):
                return tmp
            i = tmp+1
        return -1
  • java: 不需要检查haystack所有元素
(Implement-strStr.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
    public int strStr(String haystack, String needle) {
        if (needle.length()==0) return 0;
        if (haystack.length()==0) return -1;

        int n = haystack.length()-1;
        int m = needle.length()-1;
        for(int i=0;i<=n-m;i++){
            int j=0;
            int k = i;
            while (j<=m && haystack.charAt(k) == needle.charAt(j)){
                k+=1;
                j+=1;
            }
            if (j>m)
                return i;
        }
        return -1;
    }
}