반응형
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 <= haystack.length, needle.length <= 104haystackandneedleconsist of only lowercase English characters.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(haystack) < len(needle) :
return -1
if needle not in haystack :
return -1
for left in range(len(haystack)) :
right = left
while haystack[right] == needle[right - left] :
right += 1
if len(needle) == right - left :
return left
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n, m = len(haystack), len(needle)
if n < m :
return -1
if needle not in haystack :
return -1
for left in range(n) :
if haystack[left:left+m] == needle :
return left
return -1
딱히 풀이가 필요없는 문제라고 생각한다. 첫 글자를 하나 잡아서 needle의 길이만큼 잡았을 때, needle 과 동일하면 정답처리. 문제대로만 풀이하면 어려움 없이 해결이 가능하다.
반응형
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 102. Binary Tree Level Order Traversal (0) | 2026.03.01 |
|---|---|
| [Leetcode/파이썬] 108. Convert Sorted Array to Binary Search Tree (0) | 2026.03.01 |
| [Leetcode/파이썬] 173. Binary Search Tree Iterator (0) | 2026.02.21 |
| [Leetcode/파이썬] 70. Climbing Stairs (0) | 2026.02.21 |
| [Leetcode/파이썬] 199. Binary Tree Right Side View (0) | 2026.02.21 |