28.字符串第一个匹配的下标

741 阅读1分钟

28.字符串第一个匹配的下标

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回  -1 。

输入:haystack = "sadbutsad", needle = "sad"
输出:0

class Solution {
    public int strStr(String haystack, String needle) {
        int m = haystack.length();
        int n = needle.length();
        char[] hh= haystack.toCharArray();
        char[] nn= needle.toCharArray();
        for(int i = 0; i <= m - n; i++){
            int a = i;
            int b = 0;
            while(b < n && hh[a] == nn[b]){
                a++;
                b++;
            }
            if(b == n) return i;
        }
        return -1;
    }
}