image.png
    暴力匹配

    1. class Solution {
    2. public int strStr(String haystack, String needle) {
    3. int sLen = haystack.length();// 主字符串
    4. int pLen = needle.length();// 模式串长度
    5. // 需要匹配的次数
    6. for (int i=0;i<=sLen-pLen;i++){
    7. int j ;
    8. // 遍历模式串
    9. for (j=0;j<pLen;j++){
    10. if (needle.charAt(j)!=haystack.charAt(i+j)){
    11. break;
    12. }
    13. }
    14. // 如果j移动到模板末尾了 说明匹配成功了
    15. if (j==pLen) return i ;
    16. }
    17. return -1;
    18. }
    19. }