28. Implement strStr()

来源:互联网 发布:开淘宝网店怎样找货源 编辑:程序博客网 时间:2024/05/21 17:44

题目:https://leetcode.com/problems/implement-strstr/

代码:

public class Solution {    public int strStr(String haystack, String needle) {        if(needle.length()>haystack.length())            return -1;        return haystack.indexOf(needle);    }}用String的自带函数1ms=======================public class Solution {    public int strStr(String haystack, String needle) {        if(needle.length()>haystack.length())            return -1;        int lengthh = haystack.length();        int lengthn = needle.length();        int index=0,i,j;        while(lengthh>=lengthn)        {            i=0;            j = index;            int flag = 0;            while(i<lengthn)            {                if(haystack.charAt(j)!=needle.charAt(i))                {                    flag = 1;                    break;                }                i++;j++;            }            if(flag == 0)                return index;            else            {                index++;lengthh--;            }        }        return -1;    }}4ms
0 0
原创粉丝点击