zoukankan      html  css  js  c++  java
  • Implement strStr() leetcode

    Implement strStr().

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

    Update (2014-11-02):
    The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

    解题:我用的方法相当于暴力破解:int strStr(string haystack, string needle) ;

      首先,遍历haystack,依次寻找第一个与needle第一个字符匹配的位置,同时记录相对于该位置的下一个位置(我记为ret,一旦接下来的匹配不成功,重新遍历haystack时,就从ret开始),如果遍历完haystack都没匹配成功,则返回-1。注意边界条件!!

      我的源代码如下:

     1 class Solution {
     2 public:
     3     int strStr(string haystack, string needle) {
     4         if(needle.empty())
     5             return 0;
     6         if (haystack.empty())
     7         {
     8             if(!needle.empty())
     9                 return -1;
    10         }
    11         if(needle.size()>haystack.size())
    12             return -1;
    13         int index = 0, reset = -1;
    14         while (index < haystack.size())
    15         {
    16             if (haystack[index] != needle[0])
    17             {
    18                 index++;
    19                 continue;
    20             }
    21             reset = index + 1;
    22             int i;
    23             for ( i = 1;index+needle.size()<=haystack.size()&& i < needle.size(); ++i)
    24             {
    25                 if (haystack[index + i] != needle[i])
    26                     break;
    27             }
    28             if (i == needle.size())
    29                 return index ;
    30             else index = reset;
    31         }
    32         return -1;
    33     }
    34 };
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    异常:This application has no explicit mapping for /error, so you are seeing this as a fallback.
    IDEA选中下一个相同内容
    IDEA Springmvc 部署本地Tomcat服务器,访问主页报404错误-问题总结
    java知识点记录
    学期总结
    今日收获
    今日收获
    今日收获
    期末总结
    每日日报
  • 原文地址:https://www.cnblogs.com/chess/p/4896520.html
Copyright © 2011-2022 走看看