#28 Implement strStr()

Description

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

Examples

Example 1:

Input: haystack = “hello”, needle = “ll”
Output: 2

Example 2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

解题思路

字符串匹配
需要注意的是如果needle是空的话返回的值是0
那就haystack一个一个走

不匹配,haystack ++
在这里插入图片描述
不匹配,haystack ++
在这里插入图片描述
配上了,haystack ++,同时needle ++
在这里插入图片描述
又不匹配了,haystack回到haystack_index - needle_index,然后再++
needle回到0
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
比较直观的体现出haystack = haystack - needle + 1的情况
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
最后发现needle走完了,也就结束了
返回haystack - needle,就是匹配的位置啦

class Solution {
    public int strStr(String haystack, String needle) {
        int i, j;
        j = 0;
        int len1 = needle.length();
        int len2 = haystack.length();
        if(len1 == 0)
            return 0;
        for(i = 0; i < len2; i++){
            if(haystack.charAt(i) == needle.charAt(j))
                j++;
            else{
                i = i - j;
                j = 0;
            }
            if(j == len1)
                break;
        }
        if(j != len1)
            return -1;
        return i - j + 1;
    }
}

不正常解法

嗯没错
我尝试了一下
java自带的
indexOf函数
甚至不需要判断
就一行代码
超越了100%的java用户
fine

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

猜你喜欢

转载自blog.csdn.net/YY_Tina/article/details/86759603