Find the Index of the First Occurrence in a String

이재하·2023년 11월 26일
0

Problem

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.

Code

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

        int n = haystack.length();
        int m = needle.length();

        for (int i = 0; i <= n - m; i++) {
            int j;
            for (j = 0; j < m; j++) {
                if (haystack.charAt(i + j) != needle.charAt(j)) {
                    break;
                }
            }
            if (j == m) {
                return i;
            }
        }

        return -1;
    }
}

이 함수는 간단한 두 개의 중첩된 루프를 사용하여 문자열을 검색한다. 바깥쪽 루프는 haystack을 처음부터 끝까지 이동하며, 안쪽 루프는 needle의 각 문자를 haystack에서 대응하는 위치에 있는 문자와 비교한다. 일치하지 않는 경우 내부 루프를 중단하고 계속 진행한다. 내부 루프가 정상적으로 종료되면, needle이 haystack에서 발견된 것으로 판단하고 해당 위치를 반환한다. 만약 전체 검색에서 일치하는 부분을 찾지 못하면 -1을 반환한다.

0개의 댓글