IT/LeetCode

[LeetCode] 28. Implement strStr()

강천구 2022. 7. 22. 18:36

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

 

반응형