首页 > 其他 > 详细

[Leetcode] implement strStr()

时间:2015-09-30 09:41:54      阅读:157      评论:0      收藏:0      [点我收藏+]

implement strStr()

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

brute force

don’t overlook this simple question. be careful on the details.


edgecase:

haystack == null?  false

needle == null?      false

needle isEmpty()??  0

 

    public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        if(needle.length() == 0) return 0;
        //haystack "aaa"
        //needle "a"
        for(int i = 0; i < haystack.length()-needle.length()+1; i++){
    
            if(haystack.charAt(i) == needle.charAt(0)){
                int j = 1;
                for(; j < needle.length(); j++){
                    if(haystack.charAt(i+j) != needle.charAt(j)){
                        break;
                    }
                }
            
                if(j == needle.length()) return i;
            }
        }
        return -1;
        
    }

 

[Leetcode] implement strStr()

原文:http://www.cnblogs.com/momoco/p/4848141.html

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