본문 바로가기
Problem Solving/LeetCode

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

by graycode 2026. 5. 16.

 문제 링크

 

Find the Index of the First Occurrence in a String - LeetCode

Can you solve this real interview question? 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: I

leetcode.com

 

 풀이 코드

public class Solution {

    public int strStr(String haystack, String needle) {
        int n = haystack.length() - needle.length() + 1, m = needle.length();
        for (int i = 0; i < n; i++)
            if (haystack.charAt(i) == needle.charAt(0) && compare(haystack, needle, m, i)) return i;

        return -1;
    }

    private boolean compare(String a, String b, int m, int i) {
        for (int j = 1; j < m; j++) if (a.charAt(i + j) != b.charAt(j)) return false;

        return true;
    }

}

댓글