zoukankan      html  css  js  c++  java
  • 028实现strStr()

     1 #pragma once
     2 #include "000库函数.h"
     3 
     4 /*********************自解**************/
     5 //使用算法中的find       12ms
     6 class Solution {
     7 public:
     8     int strStr(string haystack, string needle) {
     9         if (haystack.size() == 0 && needle.size() != 0)return -1;
    10         if (needle.size() == 0)return 0;
    11         return haystack.find(needle);
    12     }
    13 };
    14 
    15 
    16 /********************博客解法*****************/
    17 //使用暴力遍寻法        44ms
    18 class Solution {
    19 public:
    20     int strStr(string haystack, string needle) {
    21         if (needle.empty()) return 0;
    22         int m = haystack.size(), n = needle.size();
    23         if (m < n) return -1;
    24         for (int i = 0; i <= m - n; ++i) {
    25             int j = 0;
    26             for (j = 0; j < n; ++j) {
    27                 if (haystack[i + j] != needle[j]) break;
    28             }
    29             if (j == n) return i;
    30         }
    31         return -1;
    32     }
    33 };
    34 
    35 void T028() {
    36     string haystack, needle;
    37     haystack = "hello";
    38     needle = "ll";
    39     Solution s;
    40     cout << s.strStr(haystack, needle) << endl;
    41     haystack = "aaaaa";
    42     needle = "bba";
    43     cout << s.strStr(haystack, needle) << endl;
    44 }
  • 相关阅读:
    orm 锁 和 事务
    多表查询
    django 单表查询
    djgango装饰器
    几个SQL命令的使用
    怎么成为优秀的软件模型设计者?
    jbpm 工作流(二)
    Jbpm工作流(一)
    EJB 介绍
    JNDI 使用
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10530506.html
Copyright © 2011-2022 走看看