LeetCode—28. Implement strStr()

Type:easy

Implement strStr().

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

Example 1:

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

Example 2:

Input:haystack = "aaaaa", needle = "bba"Output:-1


给定一个haystack字符串和一个needle字符串,要求返回needle第一次出现在haystack中的位置,若没有则返回-1.

开两个for循环,外循环是遍历haystack的长度,内循环是遍历needle的长度。若haystack[i] != needle[j],则跳出内循环,i++,当内循环结束后 j 等于needle的长度,则说明needle在haystack中,返回i即可。

注意,当内循环结束后,j首先++,因此 j = l时,跳出内循环。


class Solution {

public:

    int strStr(string haystack, string needle) {

        int l = needle.length();

        int n = haystack.length();

        int j;

        if(n

        if(l == 0) return 0;

        for(int i=0; i

            for(j=0; j

                if(haystack[i+j] != needle[j])  break;

            }

            if(j == l) return i;

        }

        return -1;

    }

};

你可能感兴趣的:(LeetCode—28. Implement strStr())