[LeetCode] Implement strStr()

429 查看

Problem

Implement strStr().

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

Note

有substring,为何不用。

Solution

public class Solution {
    public int strStr(String h, String n) {
        int len = n.length();
        for (int i = 0; i <= h.length()-len; i++) {
            if (h.substring(i, i+len).equals(n)) return i;
        }
        return -1;
    }