Search This Blog

Tuesday, December 18, 2012

LeetCode:Implement strStr()

Implement strStr()
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
C++:

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (!*needle) 
            return haystack;
        char *start1 = haystack;
        char *start2 = needle+1;
        while (*start2) {
            ++start1;
            ++start2;
        }
        
        while (*start1) {
            char *temp1 = needle;
            char *temp2 = haystack;
            while (*temp1 && *temp2 && *temp1 == *temp2) {
                ++temp1;
                ++temp2;
            }
            if (!*temp1) 
                return haystack;
            ++haystack;
            ++start1;
        }
        return NULL;
    }
};




Java:
public class Solution {
    public String strStr(String haystack, String needle) {
        // Start typing your Java solution below
        // DO NOT write main() function
        assert(haystack!=null && needle!=null);
        if(needle.length()==0) return haystack;
        
        int i=0;
        while(i<haystack.length()){
            if(haystack.length()-i<needle.length()) 
                break;
            if(haystack.charAt(i)==needle.charAt(0)){
                int j=i;
                while(j-i<needle.length() && haystack.charAt(j)==needle.charAt(j-i))
                    j++;
                if(j-i==needle.length()) 
                    return haystack.substring(i);
            }
            i++;
        }
        return null;
    }
}

No comments: