[LeetCode]028. Implement strStr()

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

Solution: use two pointers.

Running Time: O(n). 

also can be solved by KMP, hash function, to be continued...

考虑了一下,虽然只有一个while循环,但是每当不等的时候,index1 需要向前重置,似乎运行时间是O((m-n)m)?

public class Solution {
    public String strStr(String haystack, String needle) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(needle == null || haystack == null){
            return haystack;
        }
        int len1 = haystack.length();
        int len2 = needle.length();
        int start = 0;
        int index1 = 0;
        int index2 = 0;
        while(index1<len1 && index2<len2){
            if(needle.charAt(index2) == haystack.charAt(index1)){
                index1++;
                index2++;
            }else{
                start++;
                index1 = start;
                index2 = 0;
            }
        }
        if(index2==len2 && index1==len2+start){
            return haystack.substring(start);
        }else{
            return null;
        }
    }
}


你可能感兴趣的:(LeetCode)