Leetcode

28. Find the Index of the First Occurrence in a String

Doromi 2024. 5. 2. 15:38
728x90
반응형

haystack 문자열에서 needle 문자열이 처음으로 나타나는 위치를 찾아 반환합니다. 

만약 needle 문자열이 haystack 문자열에 없다면 -1을 반환합니다. 

또한, needle 문자열이 비어있는 경우는 haystack 문자열의 시작 위치인 0을 반환합니다.

 

public class Solution {
    public int StrStr(string haystack, string needle) {
        if(string.IsNullOrEmpty(needle)) return 0;

        for(int i = 0;i <= haystack.Length-needle.Length;i++){
            if(haystack.Substring(i,needle.Length) == needle){
                return i;
            }
        }
        return -1;
    }
}
 haystack 문자열의 각 위치에서 시작하여 needle 문자열의 길이만큼의 부분 문자열이 needle 문자열과 일치하는지 확인합니다. 이 방법은 문자열 검색 알고리즘의 기본적인 형태입니다. 
이 코드의 시간 복잡도는 O(nm)입니다.
여기서 n은 haystack 문자열의 길이이고, m은 needle 문자열의 길이입니다.
이는 haystack 문자열의 각 위치에서 needle 문자열의 길이만큼의 부분 문자열을 비교하기 때문입니다.

 

728x90
반응형