[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

 

转载于:https://www.cnblogs.com/codingEskimo/p/6517679.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值