首页 > 其他 > 详细

[LeetCode]28 Implement strStr()

时间:2015-01-02 16:09:09      阅读:258      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/implement-strstr/

http://fisherlei.blogspot.com/2012/12/leetcode-implement-strstr.html

public class Solution {
    public int strStr(String haystack, String needle) {
        
        // 遍历haystack,对每一个字符,匹配needle
        
        if (haystack == null || needle == null)
            return -1;
        
        char[] h = haystack.toCharArray();
        char[] n = needle.toCharArray();
        
        for (int i = 0 ; i < h.length - n.length + 1 ; i ++)
        {
            if (match(h, i, n))
                return i;
        }
        return -1;
    }
    
    private boolean match(char[] h, int start, char[] n)
    {
        for (int i = 0 ; i < n.length ; i ++)
        {
            if ((start + i >= h.length) || (h[start + i] != n[i]))
                return false;
        }
        return true;
    }
    
    // Check KMP
}


[LeetCode]28 Implement strStr()

原文:http://7371901.blog.51cto.com/7361901/1598429

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!