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

LeetCode 28: Implement Strstr

时间:2017-08-30 15:45:52      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:length   ica   can   tco   div   boolean   while   pattern   ret   

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

标签:length   ica   can   tco   div   boolean   while   pattern   ret   

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

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