[LeetCode] Find the Index of the First Occurrence in a String (Python)

2025. 1. 15. 16:07·코딩 테스트
728x90

1.문제

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150

 

2.풀이

더 짧은 길이인 needle 문자열이 haystack 에 포함되어있는지 체크

이중포문을 돌지않는게 포인트!

다른 사람 코드를 보니 index 를 찾는 python method 가 있었다.

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle in haystack:
            index1 = haystack.index(needle)
            return index1
        else:
            return -1

 

3.코드

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        n = len(needle)
        for i in range(len(haystack)):
            curWord = haystack[i:i+n]
            if (curWord == needle):
                return i
        return -1
728x90
저작자표시 비영리 변경금지 (새창열림)

'코딩 테스트' 카테고리의 다른 글

[LeetCode] Valid Parentheses (Python)  (0) 2025.01.15
[LeetCode] RansomNote (Python)  (0) 2025.01.15
[LeetCode] 14.Longest Common Prefix (Python)  (0) 2025.01.15
[LeetCode] Length of Last Word (Python)  (0) 2025.01.15
[LeetCode] Roman to Integer  (0) 2025.01.14
'코딩 테스트' 카테고리의 다른 글
  • [LeetCode] Valid Parentheses (Python)
  • [LeetCode] RansomNote (Python)
  • [LeetCode] 14.Longest Common Prefix (Python)
  • [LeetCode] Length of Last Word (Python)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    금융용어
    코딜리티
    pythoncodingtest
    코딩
    LeetCode
    MySQL
    리트코드
    자바
    알고리즘
    C++
    쿠버네티스
    코테공부
    코테
    코딩테스트
    Python
    스프링부트
    이분탐색
    자료구조
    db
    네트워크
    프로그래머스
    Spring
    CodingTest
    codility
    java
    카카오코테
    Kotlin
    스프링
    kafka
    springboot
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[LeetCode] Find the Index of the First Occurrence in a String (Python)
상단으로

티스토리툴바