[LeetCode] Top Interview 150 Problems Solving # 28 Find the Index of the First Occurrence in a String
Understanding the Problem
There are two strings given as haystack and needle. needle is the string that could be included in haystack or not included. If it is included, return the first index that needle occurs. If it is not included in haystack, return -1.
For example, if haystack = "sadbutsad" and needle = "sad", the string ”sad” occurs at the index 0 and 6, so return 0.
Approach
My approach is to check whether needle is in haystack, then find the first index.
Solution
Check if
needleis inhaystackbyif needle in haystackclauseIf it exists in
haystack, then usefind()method to get the first index of theneedleand return itIf it does not exist in
haystack, return-1
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle) if needle in haystack else -1
Reflection
I was wondering if I should use two pointers to solve this problem, but no need for that, as there are internal functions and methods to use.
About the author
South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?
Comments
Join the discussionNo comments yet. Be the first to comment.




