http://oj.leetcode.com/problems/implement-strstr/

判断一个串是否为另一个串的子串

比较简单的方法,复杂度为O(m*n),另外还可以用KMP时间复杂度为O(m+n),之前面试的时候遇到过。

class Solution {
public:
bool isEqual(char *a,char *b)
{
char* chPointer = a;
char* chPointer2 = b;
while(*chPointer2!= '\0' && *chPointer!='\0' )
{
if(*chPointer == *chPointer2)
{
chPointer++;
chPointer2++;
}
else
return false;
}
return true;
}
char *strStr(char *haystack, char *needle) {
char* chPointer = haystack;
char* chPointer2 = needle;
if(haystack == NULL || needle ==NULL || haystack =="")
return NULL;
while(chPointer)
{
if(isEqual(chPointer,needle))
return chPointer;
chPointer++;
}
return NULL;
}
};
class Solution {
public:
void compute_prefix(const char* pattern,int next[])
{
int i;
int j = -;
const int m = strlen(pattern);
next[] = j;
for(i =;i<m;i++)
{
while(j>- && pattern[j+] != pattern[i]) j = next[j];
if(pattern[i]== pattern[j+])
j++;
next[i] = j;
}
}
int kmp(const char* text , const char* pattern)
{
int i;
int j = -;
const int n = strlen(text);
const int m = strlen(pattern);
if(n == m && m==)
return ;
if(m == )
return ;
int *next = (int *)malloc(sizeof(int) * m); compute_prefix(pattern, next); for(i = ;i <n;i++)
{
while(j >- && pattern[j+] != text[i])
j = next[j];
if(text[i] == pattern[j+]) j++;
if(j==m-)
{
free(next);
return i-j;
}
}
}
char *strStr(char *haystack, char *needle) {
int position = kmp(haystack,needle);
if(position == -)
return NULL;
else
return (char*)haystack + position;
}
};

最新文章

  1. 问题:QXcbConnection: Could not connect to display
  2. 关于SQLSERVER联合查询一点看法
  3. Ubuntu中安装eclipse ,双击eclipse出现invalid configuration location问题
  4. [Java Web] 3、WEB开发之HTML基础程序试手
  5. RDLC报表系列--------行分组报表
  6. codevs 1835 魔法猪学院 A*寻k短路做了一个月卡死在spfa那了/(ㄒoㄒ)/~~
  7. 获得临时文件目录(Temp文件夹)
  8. 1057 - Collecting Gold (状态压缩DP)
  9. PowerShell_零基础自学课程_5_自定义PowerShell环境及Powershell中的基本概念
  10. juqery合成事件toggle方法
  11. centos 虚拟机桥接
  12. Mongodb_基本操作UCRD
  13. pycharm linux版快捷方式创建
  14. 解决ssh连接问题2
  15. 使用Java类加载SpringBoot、SpringCloud配置文件
  16. 未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\2da42acc\ab2935
  17. pycharm如何在debug的时候动态执行python语句
  18. Android 进程保活招式大全(转载)
  19. cocos2d-x C++ iOS工程集成第三方支付宝支付功能
  20. C++基础知识:类的静态成员

热门文章

  1. CPP-基础:TCHAR
  2. Linux系统GEDIT编译运行C++
  3. kubernetes添加不了google apt-key
  4. Js自学学习-笔记6-8
  5. java在线聊天项目0.1版本 制作客户端窗体,使用swing(用户界面开发工具包)和awt(抽象窗口工具包)
  6. 674. Longest Continuous Increasing Subsequence@python
  7. linux 5.7.20和5.6.38版本 数据库忘记root密码怎么找回?
  8. 【Java基础】java中的反射机制与动态代理
  9. The twelve Day-前端之html
  10. raywenderlich.com Objective-C编码规范