Skip to content

28. Implement strStr()

https://leetcode.com/problems/implement-strstr/

c++
class Solution {
public:
    int strStr(string haystack, string needle) {
        int m = haystack.length();
        int n = needle.length();
        if (n == 0) {
            return 0;
        }
        if (m < n) {
            return -1;
        }
        for (int i = 0; i < m - n; i++) {
            int j = 0 ;
            while (j < n && haystack[i + j] == needle[j]) {
                j++;
            }
            if (j == n) {
                return i;
            }
        }
        return -1;
    }
};
go
func strStr(haystack string, needle string) int {
    m := len(haystack)
    n := len(needle)
    if n == 0 {
        return 0
    }
    if m < n {
        return -1
    }
    for i := 0; i < m-n; i++ {
        j := 0
        for j < n && haystack[i+j] == needle[j] {
            j++
        }
        if j == n {
            return i
        }
    }
    return -1
}
js
/**
 * @param {string} haystack
 * @param {string} needle
 * @return {number}
 */
var strStr = function(haystack, needle) {
  const m = haystack.length
  const n = needle.length
  if (n == 0) {
    return 0
  }
  if (m < n) {
    return -1
  }
  for (let i = 0; i < m - n; i++) {
    let j = 0
    while (j < n && haystack[i + j] === needle[j]) {
        j++
    }
    if (j == n) {
        return i
    }
  }
  return -1
};
py
class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        m, n = len(haystack), len(needle)
        if n == 0:
            return 0
        if m < n:
            return -1
        for i in range(0, m - n):
            j = 0
            while j < n and haystack[i + j] == needle[j]:
                j += 1
            if j == n:
                return i
        return -1