博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Implement strStr()
阅读量:7056 次
发布时间:2019-06-28

本文共 965 字,大约阅读时间需要 3 分钟。

Question: 

题目:

Implement strStr().

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


 Solutions:

  1. Naive Solution 很容易实现。O(n2) runtime.
  2. Rolling Hash.  之前也实现过,O(n) runtime. 可是 hashcode 容易溢出,并且无法保证完全没有 Conflict。 减少 Conflict 可能性,是采用 BigInteger 来记录 hashcode 的值。
  3. KMP Tutorial: 基本思路是寻找 pattern String 的 Prefix Pattern,不难理解

Naive Solution:

1 public int strStr(String haystack, String needle) { 2     if(haystack == null) { 3         return -1; 4     } 5      6     if(needle == null) { 7         return haystack.length(); 8     } 9     10     if(haystack.length() < needle.length()) {11         return -1;12     }13     14     for(int i = 0; i <= haystack.length() - needle.length(); i++) {15         String tmp = haystack.substring(i, i+needle.length());16         if(tmp.equals(needle)) {17             return i;18         }19     }20     21     return -1;22 }

 

转载于:https://www.cnblogs.com/Phoenix-Fearless/p/5120060.html

你可能感兴趣的文章
红黑树
查看>>
远程推送脚本,创建任务计划
查看>>
设计模式 工厂和抽象工厂
查看>>
Maven学习第1期---Maven简单介绍
查看>>
#include <bits/stdc++.h>头文件
查看>>
iOS swift 语句只能写在函数体内
查看>>
C# 接收form表单中多个相同name值的问题
查看>>
Eclipse下配置使用Hadoop插件
查看>>
5/3上午
查看>>
回顾“.NET技术”.NET Remoting分布式开发
查看>>
移动开发多平台代码共享“.NET研究”
查看>>
Convert IPv6 Address to IP numbers (C#)
查看>>
总是弹出visual studio 实时调试器 三种解决办法
查看>>
12岁男孩发现Firefox严重安全漏洞获奖3000美元
查看>>
谷歌发安全警告:社交网络威胁用户隐私
查看>>
一起谈.NET技术,System.DateTime详解
查看>>
一起谈.NET技术,VS2010技巧:如何在js文件中使用jQuery智能感知
查看>>
一道有趣的JS问题
查看>>
安卓开发中的一些经验总结
查看>>
HTML5规范的本地存储
查看>>