Leetcode/Top Interview 150

[Array/String][Easy] 28. Find the Index of the First Occurrence in a String

자전거통학 2024. 5. 2. 01:19

https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description

 

Q. 주어진 문자열 haystack에서 needle이 등장하는 첫번째 index를 반환하라. 

 

 

Solution. 

haystack.IndexOf(needle);

를 사용하면 한번에 찾아 질 것이다. 

 

그렇지만, 로직대로 만들어 보면, 

needle과 같은 문자로 haystack이 시작하면 그 뒤로 끝까지 같나 확인 한다. 

도중에 index 범위체크등을 넣어 준다. 

 

더보기
public int StrStr(string haystack, string needle) 
{        
    if(haystack.Length < needle.Length)
        return -1;

    for(int q = 0; q < haystack.Length; ++q)
    {
        char cur = haystack[q];
        if(cur != needle[0])    continue;
        bool match = true;
        for(int k = 0; k < needle.Length; ++k)
        {
            if(q+k>=haystack.Length || (q+k<haystack.Length && haystack[q+k]!=needle[k]))
            {
                match = false;
                break;
            }
        }
        if(match) return q;
    }
    return -1;
}

 

결과.