본문 바로가기
IT/LeetCode

[LeetCode] 28. Implement strStr()

by 강천구 2022. 7. 22.

Implement strStr().

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.

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

 

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

 

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

주어진 문장(haystack)에서 특정 문자열(needle)이 존재하는 여부와 위치를 찾는 문제이다.

python string의 find() 함수를 이용하여 결과를 전달해주도록 하면 된다.

 

class Solution:
   def strStr(self, haystack, needle):
       if haystack.find(needle) < 0 :
           return -1
       else :
           return haystack.find(needle)

 

 

문제 출처 : https://leetcode.com/problems/implement-strstr/

 

Implement strStr() - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_28.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 38. Count and Say  (0) 2022.07.22
[LeetCode] 35. Search Insert Position  (0) 2022.07.22
[Leetcode] 27. Remove Element  (0) 2022.07.22
[LeetCode] 26. Remove Duplicates from Sorted Array  (0) 2022.07.22
[LeetCode] 21. Merge Two Sorted Lists  (0) 2022.07.21

댓글