saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 릿코드
  • 취준
  • 온라인저지
  • LeetCode
  • BFS
  • 개발자
  • 파이썬
  • 알고리즘
  • DFS
  • 딥러닝
  • 딕셔너리
  • 백준
  • Python
  • 취업준비
  • 문제해결능력
  • c++
  • 개발자 취업준비
  • 리트코드
  • two pointer
  • 알고리즘문제해결

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeetCode] 28. Implement strStr()

2022. 8. 17. 14:05

28. Implement strStr()

Easy

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.

문제 풀이

문제 접근

  1. 두가지 문자의 길이가 최대 10^4 이다.
  2. N^2 시간복잡도로 풀 수도 있을 것 같다. 

풀이

  1. neelde 단어가 haystack에 존재할때, 가장 앞에있는 단어를 찾아야한다.
  2. 맨 앞 부터 탐색을 해야 제일 첫번째 인덱스를 구할 수 있다.
  3. 각 인덱스를 needle 단어와 같은지 확인한다.

소스 코드 

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        for i in range(len(haystack) - n + 1):
            temp = haystack[i:i+n]
            if temp == needle:
                return i
        return -1
저작자표시 (새창열림)

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

[LeetCode]1338. Reduce Array Size to The Half  (0) 2022.08.20
[LeetCode] 1570. Dot Product of Two Sparse Vectors  (0) 2022.08.18
[LeetCode] 49. Group Anagrams  (0) 2022.08.17
[LeetCode] 804. Unique Morse Code Words  (0) 2022.08.17
[LeetCode] 5. Longest Palindromic Substring  (0) 2022.08.16
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • [LeetCode]1338. Reduce Array Size to The Half
    • [LeetCode] 1570. Dot Product of Two Sparse Vectors
    • [LeetCode] 49. Group Anagrams
    • [LeetCode] 804. Unique Morse Code Words
    saurus2
    saurus2
    Simple is Best

    티스토리툴바