본문 바로가기
Beakjoon&프로그래머스/Java

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

by 현장 2025. 11. 20.

-Code

class Solution {
    public int strStr(String haystack, String needle) {
        int haystackLen= haystack.length();
        int needleLen = needle.length();
		
        for (int i = 0; i <= haystackLen - needleLen; i++) {
            // 현제 index에서 needle의 길이만큼 자르기
            String now = haystack.substring(i, i + needleLen);
            // 일치하면 반환
            if(now.equals(needle)) return i;
        }
        // 일치하는게 없으면 -1 반환
        return -1;
    }
}