STRSTRを(達成するための28個の質問)

題しI、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