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

    真不容易。不靠debug写出来的。纸上分析的时候,写下i和j为两行,然后一个一个的写下改变的值,这样可以找到bug。

    #include <cstring>
    #include <malloc.h>
     
    using namespace std;
     
    class Solution {
    public:
        char *strStr(char *haystack, char *needle) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            int needle_len = strlen(needle);
            int haystack_len = strlen(haystack);
            if (needle_len == 0) return haystack;
            if (haystack_len == 0) return 0;
     
            char* next = new char[needle_len];
            getNext(needle, next, needle_len);
     
            int i = 0;
            int j = 0;
             
            while (j < needle_len && i < haystack_len)
            {
                if (j == -1 || haystack[i] == needle[j])
                {
                    i++;
                    j++;
                }
                else
                {
                    j = next[j];
                }
            }
     
            free(next);
            if (j == needle_len)
                return haystack+i-j;
            else
                return 0;
        }
     
        void getNext(char *needle, char * next, int len) {
            if (len == 0) return;
     
            int i = 0;
            int k = -1;
            next[0] = -1;
            while (i < len - 1)
            {
                if (k == -1|| needle[i] == needle[k]) {
                    i++;
                    k++;
                    next[i] = k;
                }
                else {
                    k = next[k];
                }
            }
        }
    };
    

    python3,简单的双指针循环

    class Solution:
        def strStr(self, haystack: str, needle: str) -> int:
            if len(needle) == 0:
                return 0
            for i in range(len(haystack)):
                if (i + len(needle)) <= len(haystack):
                    flag = True
                    for j in range(len(needle)):
                        if haystack[i + j] != needle[j]:
                            flag = False
                            break
                    if flag:
                        return i
            return -1
                    
    

      

      

  • 相关阅读:
    Ansiable Manage MySQL global variables
    Ansible 从MySQL数据库添加或删除用户
    Ansible 管理MySQL主从复制
    Ansible 从远程主机添加或删除MySQL数据库
    vi/vim编辑器
    shell doc
    ubuntu 上 SSH scp 技巧
    SpringBoot 整合 devtools 实现热部署
    Gson 解决时间解析问题
    springboot retry
  • 原文地址:https://www.cnblogs.com/lautsie/p/3228929.html
Copyright © 2011-2022 走看看