28. Implement strStr()

    xiaoxiao2022-06-23  16

    Implement strStr().

    Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

    最直接的方式: 从头开始逐渐匹配,若不一样,则后移一位继续比较.

    时间复杂度:O(M*N) M/N分别为两个字符串的长度

    public int strStr(String haystack, String needle) { if(needle==null||haystack==null) return -1; int len1=haystack.length(); int len2=needle.length(); if(len2>len1) return -1; int j; for(int i=0;i<len1-len2+1;i++){ for(j=0;j<len2;j++){ if(haystack.charAt(i+j)!=needle.charAt(j)) break; } if(j==len2) return i; } return -1; }

    转载请注明原文地址: https://ju.6miu.com/read-1123377.html

    最新回复(0)