一、题目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();
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ↩︎