给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
如:haystack = "aaaaa", needle = "bba" 返回2
public class Solution {
public static void main(String[] args) {
String s1 = "aaaabc";
String s2 = "abc";
Solution s = new Solution();
System.out.println(s.strStr(s1, s2));
}
public int strStr(String haystack, String needle) {
if(haystack.length()==0 && needle.length()==0)return 0;
int l=needle.length();
for(int i=0;i<haystack.length()-l+1;i++){
String res = haystack.substring(i,i+l);
if(res.equals(needle)){
return i;
}
if(res!=needle){
continue;
}
}
return -1;
}
}
本文深入探讨了字符串匹配算法,特别是如何在haystack字符串中查找needle字符串首次出现的位置。通过一个具体的示例,我们展示了如何使用Java实现这一算法,并提供了详细的代码解析。
187

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



