코린이의 소소한 공부노트

[LeetCode/Medium] 28. Find the Index of the First Occurrence in a String 본문

코딩테스트 풀이/JAVA

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

무지맘 2022. 12. 26. 13:17

1. Input

1) 문자열 needle

2) 문자열 haystack

 

2. Output

1) haystack에서 needle이 처음 나타나는 인덱스를 반환

2) needlehaystack에 없다면 1을 반환

 

3. Constraint

1) 1 <= haystack.length, needle.length <= 10^4

2) haystackneedle은 영어 소문자로만 구성되어 있다.

 

4. Example

Input: haystack = "sadbutsad", needle = "sad" -> Output: 0

설명: sad0번째와 6번째에서 나타나지만, 처음 나타난 것은 0번째이므로 0을 반환한다.

 

5. Code

1) 첫 코드(2022/07/15)

int n = needle.length();
if(n == 0)
    return 0;

int h = haystack.length();
if(h < n)
    return -1;

if(h == n){
    if(haystack.equals(needle))
        return 0;
    else
        return -1;
}
 
int output = -1;
for(int i=0 ; i<h ; i++){
    if(haystack.charAt(i)==needle.charAt(0)){
        if(i+n<=h && haystack.substring(i,i+n).equals(needle)){
            output = i; break;
        }
    }
}
return output;