算法探索_实现 strStr()

问题描述:

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr

解决思路:

0.外挂手段:调用String类方法直接完事return haystack.indexOf(needle);    不推荐!没有任何的意义可言

1.首先判断一些特殊情况,直接返回

2.循环对比,只要开头字符一样,就继续往后对比,只要有一个没对上就退出内循环判断,继续下一个外循环

3.优化点:for(int j = 0; isOK == true && j < needle.length(); j++) {   

内循环 isOK 字段 同时作为 循环依据 避免 执行多余的循环

    /*
     *作者:赵星海
     *时间:2020/8/10 10:32
     *用途:实现 strStr()
     */
    public int strStr(String haystack, String needle) {
        //假如开外挂,半行代码就可以搞定,但是深海不会这么做的
        // return haystack.indexOf(needle);
        //首先判断特殊情况
        if (haystack.equals("") && needle.equals("")) return 0;
        if (needle.equals("")) return 0;
        if (!haystack.contains(needle)) return -1;
        int i;
        for (i = 0; i < haystack.length(); i++) {
            // 当前的字符与needle的第一个字符相同,则拥有判断机会
            if (haystack.charAt(i) == needle.charAt(0)) {
                boolean isOK = true;
                //依次往后对比,一旦有一个没对上,就对比失败
                for (int j = 0; isOK == true && j < needle.length(); j++) {
                    if (j >= haystack.length() || haystack.charAt(i + j) != needle.charAt(j)) {
                        isOK = false;
                    }
                }
                if (isOK) return i;
            }

        }
        return i;
    }
 

优化前提交:


优化后提交:

猜你喜欢

转载自blog.csdn.net/qq_39731011/article/details/107907474