Problem:
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
-Summary-
1. Check if needle str is in haystack str if not, return False.
2. using index() method to find the first occurrence of the needle in a haystack.
Discussion을 보니 아래와 같이 method 를 이용하지 않고 푸는 방법도 있었다.
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in range(len(haystack) - len(needle)+1):
if haystack[i:i+len(needle)] == needle:
return i
return -1
모든 문제에 대한 저작권은 LeetCode 회사에 있습니다. [Copyright © 2020 LeetCode]
'LeetCode > Top Interview Q. - Easy' 카테고리의 다른 글
LeetCode. Count and Say [String] (0) | 2020.06.03 |
---|---|
LeetCode. Longest Common Prefix [String] (0) | 2020.06.02 |
LeetCode. String to Integer (atoi) [String] (0) | 2020.06.02 |
LeetCode. Valid Palindrome [String] (0) | 2020.06.01 |
LeetCode 242. Valid Anagram (0) | 2020.05.25 |
댓글