p26 实现strStr()函数 (leetcode 28)

一:解题思路

这个题目第一种解题方法是朴素解法,时间复杂度为O(n*m)。

第二种方法就是KMP算法,用KMP算法可以将时间降低为O(m+n)。

二:完整代码示例 (C++版和Java版)

朴素解法C++:

 class Solution 
 {
 public:
     int strStr(string haystack, string needle) 
     {
         if (haystack.size() == 0 && needle.size() == 0) return 0;
         int n = haystack.size(), m = needle.size();

         for (int i = 0; i <= n - m; i++)
         {
             int j = 0, k = i;

             for (; j < m&&k < n && haystack[k] == needle[j]; k++, j++);

             if (j == needle.size()) return i;
         }

         return -1;
     }
 };

朴素解法Java:

class Solution 
{
    public int strStr(String haystack, String needle) 
    {
          if(haystack==null&&needle==null)  return 0;
          int n=haystack.length(),m=needle.length();
          
          for(int i=0;i<=n-m;i++)
          {
              int j=0,k=i;
              
              for(;j<m&&k<n && haystack.charAt(k)==needle.charAt(j);k++,j++);
              
              if(j==needle.length()) return i;
          }
          
          return -1;
    }
}

 

posted @ 2020-03-13 14:52  repinkply  阅读(156)  评论(0)    收藏  举报