Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll" Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba" Output: -1
/** * Created by lxw, liwei4939@126.com on 2018/3/5. */ public class strStr { public int strStr(String haystack, String needle){ if (haystack == null || needle == null || haystack.length() < needle.length()){ return -1; } if (needle.length() == 0){ return 0; } for (int i= 0; i < haystack.length(); i++){ if (i + needle.length() > haystack.length()){ return -1; } int m = i; for (int j = 0; j< needle.length(); j++){ if (needle.charAt(j) == haystack.charAt(m)){ if (j == needle.length() -1){ return i; } m++; } else { break; } } } return -1; } public static void main(String[] args){ strStr tmp = new strStr(); String haystack = "hello"; String needle = "lo"; System.out.print(tmp.strStr(haystack, needle)); } }
本文介绍了一个简单的字符串匹配算法实现,该算法用于查找一个字符串(haystack)中另一个字符串(needle)首次出现的位置。通过逐字符比较的方式实现了strStr()方法,并提供了具体的Java代码示例。

595

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



