코딩테스트

[leetcode] Find the Index of the First Occurrence in a String

nayoon 2024. 8. 1. 07:40

문제

 

 

class Solution {
    public int strStr(String haystack, String needle) {
        int result = -1;

        if (haystack.length() < needle.length()) {
            return result;
        }

        for(int i = 0; i <= haystack.length() - needle.length(); i++) {
            if (needle.charAt(0) == haystack.charAt(i)) {
                
                boolean same = true;
                for(int j = 0; j < needle.length(); j++) {
                    if (needle.charAt(j) != haystack.charAt(i + j)) {
                        same = false;
                        break;
                    }
                }

                if (same) {
                    result = i;
                    break;
                }
            }
        }
        return result;
    }
}