28 strStr

ImplementstrStr().

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

Example 1:

Input:
 haystack = "hello", needle = "ll"

Output:
 2

Example 2:

Input:
 haystack = "aaaaa", needle = "bba"

Output:
 -1
class Solution {
    public int strStr(String source, String target) {
        int slen = source.length();
        int tlen = target.length();
        int j;
        for (int i = 0; i < slen - tlen + 1; i++) {
            for (j = 0; j < tlen; j++) {
                if (source.charAt(i + j) != target.charAt(j)) {
                    break;
                }
            }
            if (j == tlen) {
                return i;
            }
        }
        return -1;
    }
}

results matching ""

    No results matching ""