조컴퓨터

28. Implement strStr() 본문

LeetCode/Algorithms

28. Implement strStr()

챠오위 2021. 10. 20. 00:00

 

? indexOf 로 바로 풀린다.

 

class Solution {
    public int strStr(String haystack, String needle) {
        int num = haystack.indexOf(needle);
        
        if( needle.length() == 0 ) {
            num = 0;
        }

        return num;
    }
}

 

너무 빨리 끝나서 다른 방향을 더 생각해 보았다.

 

class Solution {
    public int strStr(String haystack, String needle) {
        if( needle.length() == 0 ) return 0;
        if( haystack.length() == 0 ) return -1;
        
        int i = 0, j = 0;
        
        while( i<haystack.length() && j<needle.length() ) {
            if( haystack.charAt(i) == needle.charAt(j) ) {
                i++;
                j++;
            } else {
                i = i-j+1;
                j = 0;
            }
        }
        
        if( j == needle.length() ) {
            return i-j ;
        }
        
        return -1;
    }
}

 

 

 

'LeetCode > Algorithms' 카테고리의 다른 글

53. Maximum Subarray  (0) 2021.10.27
35. Search Insert Position  (0) 2021.10.20
27. Remove Element  (0) 2021.10.19
26. Remove Duplicates from Sorted Array  (0) 2021.10.17
*21. Merge Two Sorted Lists  (0) 2021.10.17