LeetCode 28. Implement strStr()

来源:互联网 发布:安卓手机游戏 知乎 编辑:程序博客网 时间:2024/06/05 00:39

public class Solution {    public int strStr(String haystack, String needle) {  //边界处理        if ( needle.length()==0){            return 0; //空串概念上匹配任意字符串        }        for (int i = 0; i <=haystack.length()-needle.length() ; i++) {  //剩余的比p短就不匹配了            int j = 0;            if (haystack.charAt(i) == needle.charAt(j)  ){  //第一次匹配字母OK时候记录此刻的位置i 不能修改 下一次i+1                for ( ; j <needle.length()&&i+j<haystack.length() ; j++) {                    if(haystack.charAt(i+j) != needle.charAt(j)){                        break;  //出现不相等那就break;                    }else {                        if (j == needle.length()-1)//遍历完全了 全部完成即完全匹配那就返回位置                           return i;                    }                }            }            //这里是没匹配上        }        return -1;    }}





原创粉丝点击