LeetCode //28. Find the Index of the First Occurrence in a String

28. Find the Index of the First Occurrence in a String

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

Example 1:

Input: haystack = “sadbutsad”, needle = “sad”
Output: 0
Explanation: “sad” occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = “leetcode”, needle = “leeto”
Output: -1
Explanation: “leeto” did not occur in “leetcode”, so we return -1.

Constraints:

  • 1 < = h a y s t a c k . l e n g t h , n e e d l e . l e n g t h < = 1 0 4 1 <= haystack.length, needle.length <= 10^4 1<=haystack.length,needle.length<=104
  • haystack and needle consist of only lowercase English characters.

From: LeetCode
Link: 28. Find the Index of the First Occurrence in a String


Solution:

Ideas:
The strstr function returns a pointer to the first occurrence of needle in haystack, or a null pointer if needle is not found. If needle is found, then we subtract the pointer haystack from the pointer result to get the index of the first occurrence of needle. If needle is not found, then we return -1.
Code:
int strStr(char * haystack, char * needle) {
    char *result = strstr(haystack, needle);
    if (result) {
        return result - haystack;
    } else {
        return -1;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法,c语言)