Leecode 28:实现 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() 定义相符。

思路:当haystack和needle都为空时,返回0;
当needle为空,返回0;
当haystack和needle都不为空,遍历haystack,寻找haystack中等于needle第一个字符的位置i,找到后,截取haystack字符串,截取长度从i开始,长度等于needle长度的字符串,然后比较截取后的字符串是否与needle相等,相等的话,返回i,不相等继续寻找。
注意点:在截取时,要先判断haystack是否有足够的长度供截取,如果长度不够,则直接返回-1.

class Solution {
    public int strStr(String haystack, String needle) {
        if("".equals(haystack) && "".equals(needle)) return 0;
        if("".equals(needle)) return 0;
        for(int i = 0; i < haystack.length(); i++){
            if(haystack.charAt(i) == needle.charAt(0)){
                if(needle.length() > haystack.length() - i)
                return -1;
                String temp = haystack.substring(i,i + needle.length());
                if(needle.equals(temp)){
                    return i;
                }
            }else continue;
        }
        return -1;
    }
}
发布了26 篇原创文章 · 获赞 0 · 访问量 792

猜你喜欢

转载自blog.csdn.net/u013317894/article/details/103890699
今日推荐