首页 > 其他 > 详细

Implement strStr()

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

Implement strStr().

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

 

字符串匹配问题,要注意needle 为空的情况,最简单的代码是:

public class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}

当然这样写就没啥意义了。

 

完整代码:

public class Solution {
    public int strStr(String haystack, String needle) {
        char[] hay_char = haystack.toCharArray();
        char[] needle_char = needle.toCharArray();
        int hay_size = hay_char.length;
        int needle_size = needle_char.length;
        if(needle_size == 0){
            return 0;
        }
        int dis = hay_size-needle_size;
        for(int i = 0;i <= dis;i++){
            if(needle_char[0] == hay_char[i]){
                for(int j = 0;j < needle_size;j++){
                    if(hay_char[i+j]!=needle_char[j]){
                        break;
                    }
                    if(j == needle_size-1){
                        return i;
                    }
                }
            }
        }
        return -1;
    }
}

 

Implement strStr()

原文:http://www.cnblogs.com/mrpod2g/p/4267322.html

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