【Leetcode Algorithm】Implement strStr()

来源:互联网 发布:软件行业 技术规范 编辑:程序博客网 时间:2024/05/01 06:19

Implement strStr().

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


自己的代码:

public class Solution {    public int strStr(String haystack, String needle) {        for(int i=0;i<=haystack.length()-needle.length();i++){            boolean flag = true;            for(int j=0;j<needle.length();j++){                //只要有一个字符不匹配,则匹配失败                if(haystack.charAt(i+j)!=needle.charAt(j)){                    flag = false;                    break;                   }            }            //若经过比较之后,flag==true,则匹配成功,返回i            if(flag==true){                return i;            }        }        return -1;    }}


0 0
原创粉丝点击