Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
public class Solution {
public static int strStr(String haystack, String needle) {
int hay_len = haystack.length();
int need_len = needle.length();
int pos = -1;
if(hay_len<need_len)
pos = -1;
if(hay_len == need_len)
if (!haystack.equals(needle))
pos = -1;
else pos = 0;
for(int i=0;i<hay_len-need_len+1;i++){
if (haystack.substring(i,i+need_len).equals(needle)){
pos = i;
break;
}
}
return pos;
}
public static void main(String[] args){
int pos = strStr("gasadas","aa");
System.out.println(pos);
}
}
Runtime 1ms 纯自己写的 哈哈哈!!~老开心了!