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

    可以用c的方法

     1 class Solution {
     2 public:
     3     char *strStr(char *haystack, char *needle) {
     4         // IMPORTANT: Please reset any member data you declared, as
     5         // the same Solution instance will be reused for each test case.
     6         int haylen = strlen(haystack);
     7         int needlen = strlen(needle);
     8         for (int i = 0; i <= haylen-needlen; i++) {
     9             char *p = haystack + i;
    10             char *q = needle;
    11             while (*q != '\0' && *p == *q) {
    12                 p++, q++;
    13             }
    14             if (*q == '\0') return haystack + i;
    15         }
    16         return NULL;
    17     }
    18 };

    再贴段更加清晰的代码

     1 class Solution {
     2 public:
     3     char *strStr(char *haystack, char *needle) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         string S, T;
     7         for (int i = 0; *(haystack+i) != '\0'; i++) S += *(haystack+i);
     8         for (int i = 0; *(needle+i) != '\0'; i++) T += *(needle+i);
     9         int m = S.size();
    10         int n = T.size();
    11         if (!n) return haystack;
    12         for (int i = 0; i < m-n+1; i++) {
    13             if (S.substr(i, n) == T) return haystack+i;
    14         }
    15         return NULL;
    16     }
    17 };
    1 public class Solution {
    2     public int StrStr(string haystack, string needle) {
    3         if (needle.Length == 0) return 0;
    4         for (int i = 0; i < haystack.Length - needle.Length + 1; i++) {
    5             if (haystack.Substring(i, needle.Length) == needle) return i;
    6         }
    7         return -1;
    8     }
    9 }
    View Code
  • 相关阅读:
    Redis实现分布式锁
    Redis数据结构
    Mysql与redis缓存一致性
    mysql分库分表
    mysql主从同步
    mysql配置优化
    Netty 参数优化
    JAVA多线程之park & unpack
    网络时钟服务器(网络校时服务器)无法同步的排查方法
    GPS北斗共视授时中的多径效应分析
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/2973538.html
Copyright © 2011-2022 走看看