码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]28 Implement strStr()

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

标签:leetcode

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()

标签:leetcode

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!