코딩 테스트
[LeetCode] Find the Index of the First Occurrence in a String (Python)
zoodi
2025. 1. 15. 16:07
728x90
1.문제
2.풀이
더 짧은 길이인 needle 문자열이 haystack 에 포함되어있는지 체크
이중포문을 돌지않는게 포인트!
다른 사람 코드를 보니 index 를 찾는 python method 가 있었다.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle in haystack:
index1 = haystack.index(needle)
return index1
else:
return -1
3.코드
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(needle)
for i in range(len(haystack)):
curWord = haystack[i:i+n]
if (curWord == needle):
return i
return -1
728x90