首页 > 其他 > 详细

LeetCode 28: Implement Strstr

时间:2017-08-30 14:52:47      阅读:209      评论:0      收藏:0      [点我收藏+]
class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack.length() < needle.length()) {
            return -1;
        }
        
        if (needle.length() == 0) {
            return 0;
        }

        char[] toMatch = haystack.toCharArray();
        char[] pattern = needle.toCharArray();
        for (int i = 0; i < toMatch.length - pattern.length + 1; i++) {
            if (toMatch[i] == pattern[0] && isMatch(toMatch, i, pattern, 0)) {
                return i;
            } 
        }
        return -1;
    }
    
    
    private boolean isMatch(char[] a, int i1, char[] b, int i2) {
        while (i1 < a.length && i2 < b.length && a[i1] == b[i2]) {
            i1++;
            i2++;
        }
        return i2 == b.length;
    }
}

 

We can avoid more duplicate work by check [0, haystack - needle + 1] length.

Need to revisit KMP

 

LeetCode 28: Implement Strstr

原文:http://www.cnblogs.com/shuashuashua/p/7452890.html

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