[알고리즘] leetcode - 28번

Ss·2025년 3월 18일

문제

  • 문제
    주어진 문자열 haystack과 needle이 있을 때,
    needle이 haystack 내에서 처음 나타나는 위치를 반환합니다.
    needle이 존재하지 않으면 -1을 반환합니다.

  • 조건

  1. 1 <= haystack.length, needle.length <= 10^4
  2. haystack, needle 는 영소문자로 이루어졌습니다.
  • 예시
    예제 1
    입력: haystack = "sadbutsad", needle = "sad"
    출력: 0

예제 2
입력: haystack = "leetcode", needle = "leeto"
출력: -1

풀이 결과

해결

막혔던점 혹은 이유

딱히 막힌건 없었고 남은 haystack의 길이를 체크했어야 하는걸 유의하면 될것같다.

배운점

indexOf 라는 함수를 처음 알게되었다..

런타임 가장빠른 답

class Solution {
  int strStr(String haystack, String needle) {
    for (int i = 0; i <= haystack.length - needle.length; i++) {
        int t = i + needle.length;
        if (haystack.substring(i, t) == needle) {
            return i;
        }
    }
    return -1;
  }
}

메모리 가장 적은 답

class Solution {
  int strStr(String haystack, String needle) {
    if (haystack.length == needle.length){
        if(haystack==needle){
            return 0;
        }else{
            return -1;
        }
    }else{
        for (var i = 0; i < haystack.length; i++) {
      if (needle.length == 1) {
        if (haystack[i] == needle) {
          return i;
        }
      } else {
        if (((i + (needle.length)) <= haystack.length) &&
            (haystack.substring(i, (i + (needle.length))) == needle)) {
          return i;
        }
      }
    }
    }
    

    return -1;
  }
}

0개의 댓글