题28、实现 strStr()

一、题目1

在这里插入图片描述

二、思路

方法简单粗暴,直接遍历

看题解里面有一种KMP算法,等我搞情况了再回来优化。

三、代码

public class T0028 {

    public T0028(){

//        System.out.println( strStr( "hello", "ll" ) );      //2
//        System.out.println( strStr( "aaaaa", "bba" ) );     //-1
//        System.out.println( strStr( "", "" ) );             //0
//        System.out.println( strStr( "", "a" ) );            //-1
//
//        System.out.println( strStr( "asdcasc", "as" ) );    //0
//        System.out.println( strStr( "vdsacacs", "vda" ) );  //-1
//        System.out.println( strStr( "bsdfvd", "fvs" ) );    //-1
//        System.out.println( strStr( "asncajkscn", "cn" ) ); //8
//
//        System.out.println( strStr( "aaa", "aaaaa" ) );             //-1
//        System.out.println( strStr( "mississippi", "issip" ) );             //4
        System.out.println( strStr( "aabaaabaaac" , "aabaaac") );             //4


    }

    public int strStr(String haystack, String needle) {

        if ( needle == "" || needle.equals("") )
            return 0;

        int i = 0;
        boolean content = true;

        while ( i < haystack.length() ){
            content = true;
            for ( int j = 0; j < needle.length(); j++ ){

                if ( i+j >= haystack.length() ) {
                    content = false;
                    break;
                }
                if ( haystack.charAt(i+j) != needle.charAt(j) ){
                    content = false;
                    break;
                }
            }

            if ( content )
                return i;
            else
                i++;
        }

        return -1;
    }

    public static void main(String[] args) {
        T0028 t0028 = new T0028();
    }
}


  1. 来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/implement-strstr
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ↩︎

发布了48 篇原创文章 · 获赞 1 · 访问量 837

猜你喜欢

转载自blog.csdn.net/weixin_45980031/article/details/104413338
今日推荐