zoukankan      html  css  js  c++  java
  • [LeetCode] Implement strStr()

    Implement strStr().
    
    Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

    I wrote that function before in practice without knowing anything about strStr(), so I have a pretty clear brute-force solution in my mind.

     1 class Solution {
     2 public:
     3     char *strStr(char *haystack, char *needle) {
     4         char *i = haystack;
     5         char *j = needle;
     6         int k = 0, m = 0;
     7         if (*j=='')return haystack;
     8         while (*i != ''){
     9             while (*(i+k)!='' && *(j+m)!=NULL && *(i+k) == *(j+m)){
    10                 k++;
    11                 m++;
    12             }
    13             if (k!=0 && m!= 0){
    14                 if (*(j+m) == ''){
    15                     return i;
    16                 }else{
    17                     k=0;m=0;
    18                 }
    19             }
    20             i++;
    21         }
    22         return NULL;
    23     }
    24 };

    Not very clean, with some unnecessary variable but express my thought well, unfortunately it's Time Limit Exceeded, means we can still do some optimize.
    Some people says using KMP can definitely solve the problem, but its too hard to code(for me). I don't think people will ask to write KMP during an interview.
    Then I find this thread the trick is, in fact we should aways only iterate N-M+1 times.

    my AC version:

     1 class Solution {
     2 public:
     3     char *strStr(char *haystack, char *needle) {
     4         char *i = haystack;
     5         char *j = needle;
     6         char *l = haystack;
     7         int k = 0;
     8         if (!*j)return haystack;
     9         
    10         while (*++j){
    11             l++;
    12         }
    13         j = needle;
    14         
    15         while (*l){
    16             while (*(i+k) && *(j+k) && *(i+k) == *(j+k)){
    17                 k++;
    18             }
    19             if (k!=0){
    20                 if (!*(j+k)){
    21                     return i;
    22                 }else{
    23                     k=0;
    24                 }
    25             }
    26             i++;
    27             l++;
    28         }
    29         return NULL;
    30     }
    31 };
  • 相关阅读:
    python中读取文件数据时要注意文件路径
    sklearn.model_selection 的 train_test_split作用
    matplotlib中subplot的各参数的作用
    用梯度下降算法求最值
    AfxMessageBox与MessageBox用法与区别
    MFC、API、C++三者的区别
    2、CString与string借助char *互转
    1、创建MFC应用程序——单个文档
    1、Mat类的属性、方法
    CMake编译OpenCV
  • 原文地址:https://www.cnblogs.com/agentgamer/p/3674571.html
Copyright © 2011-2022 走看看