Coding Challenges/LeetCode

[Java] 28. Find the Index of the First Occurrence in a String

기록해연 2025. 2. 14. 09:28

난이도: EASY

 

문제 링크: https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/


문제

더보기

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.

 

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

 

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

 

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.

스택으로 풀어보려했는데 각이 잘안나오고 비효율적이라 빠른 포기후 indexOf() 사용


 

주요 메소드:

int index = haystack.indexOf(needle);

 

✔ haystack에서 needle이 처음 나타나는 인덱스(위치)를 반환.
✔ needle이 haystack에 없으면 -1 반환.
✔ needle이 빈 문자열(" ")이면 항상 0 반환.

=> 해당 문제에서는 needle의 길이가 1 보다 크다는 조건이있어서 상관없음.


 

나의 최종 제출 답안:

class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}