# 28. Find the Index of the First Occurrence in a String 題目:<https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/> 解法:直接解,找到第一個字元一樣之後,才比對後續字元,比對完正確則直接回傳 index Python3: ``` python 3 class Solution: def strStr(self, haystack: str, needle: str) -> int: lenH = len(haystack) lenN = len(needle) i = 0 while (i < lenH - lenN + 1): if haystack[i] == needle[0]: j = 0 k = i while (j < lenN): if haystack[k] == needle[j]: k += 1 j += 1 else: break if j == lenN: return i i += 1 return -1 if __name__ == '__main__': haystack = "sadbutsad" needle = "sad" ans = Solution().strStr(haystack, needle) print(ans) ``` C: ``` c #include <stdio.h> #include <stdlib.h> #include <string.h> int strStr(char * haystack, char * needle) { int lenH = strlen(haystack); int lenN = strlen(needle); for (int i = 0; i < lenH - lenN + 1; i++) { if (haystack[i] == needle[0]) { int j = 0, k = i; while (j < lenN) { if (haystack[k] == needle[j]) { k++; j++; } else break; } if (j == lenN) return i; } } return -1; } int main() { char haystack[] = "sadbutsad"; char needle[] = "sad"; int ans = strStr(haystack, needle); printf("%d\n", ans); return 0; } ``` ###### tags: `leetcode` `string`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up