Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- DP
- easy
- Binary
- 이진트리
- string
- 리트코드
- linked list
- two pointers
- Medium
- 미디움
- HashTable
- matrix
- 문자열
- hash table
- binary tree
- 중간
- binary search
- list
- Python
- backtracking
- tree
- 재귀
- recursive
- 쉬움
- leetcode
- dfs
- Depth-first Search
- math
- sorting
- Array
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 28(Find the Index of the First Occurence in a String, Python) 본문
Algorithm/LeetCode
LeetCode 28(Find the Index of the First Occurence in a String, Python)
펩시_콜라 2023. 11. 3. 19:001. 문제 링크
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
2. 문제 설명
- needle, haystack을 변수명으로 하는 두가지 string이 주어졌을 때, needle이 haystack 안에서 처음으로 나타나는 위치의 인덱스를 반환, 만약 needle이 haystack에 포함되어 있지 않으면 -1을 반환
- 예시1) haystack="sadbutsad", needle="sad"이면 sad가 index 0에서 처음 등장하여, 0을 return
- 예시2) haystack="leetcode", needl="leeto"이면 "leeto"는 "leetcode"에 등장하지 않으므로, -1을 return
3. 처음 풀이
- 우선 haystack에 needle이 포함되있지 않으면 -1을 반환하고,
- 그 외의 경우에는, haystack의 index를 needle의 길이만큼 slicing하면서 needle과 같아지는 시작 index를 반환.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle not in haystack: # haystack에 needle이 없으면 -1을 반환
return -1
else:
for index, i in enumerate(haystack):
if haystack[index:index+len(needle)] == needle: # needle length만큼 index를 slicing하면서, needle과 같으면 index를 반환
return index
- runtime beat 86.3%으로 괜찮은 결과가 나왔음
4. 다른 풀이
- 애초에 python 문자열에는 .index라는 함수가 있었다.
- haystack에 needle이 없으면 -1, 있으면 haystack.index(needle)을 반환
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if needle in haystack:
return haystack.index(needle)
else:
return -1
- 더 짧게 푸는 풀이도 찾았는데, index 대신 find를 쓰면 if ~ else가 한번에 처리된다.
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
5. 배운 점
- string에 있는 몰랐던 함수들 (find, index)에 대해 알게 되었다.
- 그래도 알고리즘 배우는 관점에선 첫번째 한 풀이가 나쁘진 않은듯 하다.
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 26(Remove Duplicates from Sorted Array, Python) (0) | 2023.11.05 |
---|---|
LeetCode 27(Remove Element, Python) (0) | 2023.11.04 |
LeetCode 21(Merge Two Sorted Lists, Python) (0) | 2023.11.02 |
LeetCode 20(Valid Parentheses, Python) (0) | 2023.11.01 |
LeetCode 14(Longest Common Prefix, Python) (1) | 2023.10.31 |