美文网首页
28. Implement strStr()

28. Implement strStr()

作者: 一棵会开花的树_f654 | 来源:发表于2018-01-25 17:57 被阅读0次

    问题描述

    Implement strStr().

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

    Example 1:

    Input: haystack = "hello", needle = "ll"
    Output: 2
    

    Example 2:

    Input: haystack = "aaaaa", needle = "bba"
    Output: -1
    

    分析

    1.strStr()是C++的函数,和Java的indexOf()和substring()作用差不多,所以不能用这两个现成的函数。
    2.需要两个指针分别指向haystack和needle,双重for循环,遍历haystack与needle进行比较,只要与needle的第一个字符不同就跳出本层循环,进行haystack下个字符的比较,直到needle的所有字符都满足条件。

    代码如下:

      public int strStr(String haystack, String needle) {
            if(haystack == "") return -1;
            for(int i=0; ; i++){
                for(int j=0;;j++){
                    if(j == needle.length())    return i; //说明needle存在于haystack中
                    if(i+j == haystack.length())    return -1; //haystack已经遍历完
                    if(needle.charAt(j) != haystack.charAt(i+j))    break;
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:28. Implement strStr()

          本文链接:https://www.haomeiwen.com/subject/tpnvaxtx.html