January 27, 2019

28. Implement strStr()

28. Implement strStr()

Java:

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

Python:

class Solution:
    def strStr(self, haystack, needle):
        if not needle:
            return 0
        if not haystack:
            return -1
        for i in range(0, len(haystack) - len(needle) + 1):
            for j in range(0, len(needle)):
                if haystack[i + j] != needle[j]:
                    break
                if j == len(needle) - 1:
                    return i
        return -1
comments powered by Disqus