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 int strStr(String haystack, String needle) {
if(haystack==null||needle==null||needle.length()<0||haystack.length()<0||needle.length()>haystack.length()){return -1;}
for(int i=0;i<haystack.length()-needle.length()+1;i++){
int j=0;
for(j=0;j<needle.length();j++){
if(haystack.charAt(i+j)!=needle.charAt(j)){
break;
}
}
if(j==needle.length()){return i;}
}
return -1;
}
}
本文介绍了一个Java实现的strStr()函数,该函数用于查找一个字符串(needle)在另一个字符串(haystack)中首次出现的位置,并返回其索引。若未找到则返回-1。通过双层循环遍历对比实现这一功能。
307

被折叠的 条评论
为什么被折叠?



