# 3.2 leetcode实现 strStr()

my

class Solution {
public static void main(String[] args)
{/*
String s1 = "mississippi";
String s2 = "pi";

*/
String s1 = "mississippi";
String s2 = "issipi";
System.out.println(strStr(s1, s2));
}
public static int strStr(String haystack, String needle) {

char[] hayChar = haystack.toCharArray();
char[] neeChar = needle.toCharArray();
if (needle == null || needle.length() == 0 || haystack.equals(needle))
return 0;
else if(haystack == null || haystack.length() == 0 || haystack.length() < needle.length())
return -1;

else
int k = 0;
int n = 0;
//System.out.println("k="+k);

for1:
for(int i = 0; i < hayChar.length; i++)
{

{
k = i;//k=8
n = i;
for2:
for(int j = 0; j < neeChar.length; j++)
{

System.out.println("j="+j);
System.out.println("k="+k);
if(neeChar[j] != hayChar[k] )
continue for1;

if(k == hayChar.length-1 && j == neeChar.length-1 )
break for2;
else if (k == hayChar.length-1 && j != neeChar.length-1 )
{
return -1;
}
else
k++;

}
System.out.println("n="+n);
return n;
}

}

return -1;
}
}

public int strStr(String haystack, String needle) {
int m = haystack.length(), n = needle.length();
if (n == 0) return 0;
for (int i = 0; i <= m - n; i++) {
for (int j = 0; j < n; j++) {
if (haystack.charAt(i + j) != needle.charAt(j)) break;
if (j == n - 1) return i;
}
}
return -1;
}


class Solution {
public int strStr(String haystack, String needle) {
int L = needle.length(), n = haystack.length();

for (int start = 0; start < n - L + 1; ++start) {
if (haystack.substring(start, start + L).equals(needle)) {
return start;
}
}
return -1;
}
}



07-20 391

09-01 230
07-06 362
08-26 215
01-08 115
12-26 1978
07-08 2120
02-01 4591
04-01 4万+