[LeetCode] 28. Implement strStr

class Solution {
    /**
     * Returns a index to the first occurrence of target in source,
     * or -1  if target is not part of source.
     * @param source string to be scanned.
     * @param target string containing the sequence of characters to match.
     */
    public int strStr(String source, String target) {
        // write your code here
        if (source == null || target == null){
            return -1;
        } 
        
        for (int i = 0; i < source.length() - target.length() + 1; i++){
            int j;
            for (j = 0; j < target.length(); j++){
                if  (source.charAt(i + j) != target.charAt(j)){
                    break;
                }
            }
            
            if (j == target.length()){
                return i;
            }
        }
        
        return -1;
        
        
    }
}

Notice

1. Input String always need to be check whether it is NULL;

2. For the conner cases, source is shorter than the target or target is empty, it could be handled if the boundary is set up properly. "i < source.length() - target.length() + 1" 

3. Working with Array or List, boundary is very important. I need to think carefully about it. 

Python Version:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if haystack is None or needle is None: 
            return -1
        
        len_h = len(haystack)
        len_n = len(needle)
        if len_n == 0: return 0
        if len_h == 0: return -1
        if len_h < len_n: return -1
        
        for i in range(0, len_h - len_n + 1):
            j = 0
            while (j < len_n):
                if haystack[i + j] != needle[j]:
                    break
                j += 1 
            if j == len_n:
                return i
        return -1

 

posted on 2017-03-12 00:55  codingEskimo  阅读(142)  评论(0编辑  收藏  举报

导航