본문 바로가기

Programming/알고리즘 공부

[LeetCode] Implement strStr() | 난이도: Easy

반응형

문제

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

 

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

 

haystack에서 needle과 동일한  문자의 인덱스값을 찾는 문제.

needle에 값이 없다면 0을 리턴.


예시

Input: haystack = "hello", needle = "ll"
Output: 

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Input: haystack = "", needle = ""
Output: 0

답안

class Solution {
    public int strStr(String haystack, String needle) {

        if(needle.isEmpty() || haystack.equals(needle)) return 0;
        
        for(int i = 0; i <= haystack.length()-needle.length(); i++){
            String result = haystack.substring(i, i+needle.length());
            if(result.equals(needle)) return i;
        }
        return -1;

    }
}

substring 메서드를 사용하여 needle 문자 길이만큼 haystack 문자를 왼쪽->오른쪽으로 찾는다.

반응형