知之者 不如好之者, 好之者 不如樂之者

기계처럼 살지 말고, 즐기는 인간이 되자

Code/LeetCode

[LeetCode] 28. Find the Index of the First Occurrence in a String (Medium/Python)

코방코 2023. 3. 3. 12:26
728x90
 

Find the Index of the First Occurrence in a String - LeetCode

Can you solve this real interview question? 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: I

leetcode.com

Above is the link to the problem.

 

Problem

Given two strings variables "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 indexes 0 and 6.

We are finding the first occurrence.

So we return 0.

 

Example 2

Input: haystack = "leetcode", needle = "leeto"

Output: -1

Explanation: "leeto" did not occur in "leetcode", so we return -1.

 

Code

 

This code gets the top 1.08% of time complexity and uses 13.8MB of memory.

 

728x90
반응형