LeetCode OJ--Implement strStr()
2024-08-30 06:58:27
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;
}
};
最新文章
- 问题:QXcbConnection: Could not connect to display
- 关于SQLSERVER联合查询一点看法
- Ubuntu中安装eclipse ,双击eclipse出现invalid configuration location问题
- [Java Web] 3、WEB开发之HTML基础程序试手
- RDLC报表系列--------行分组报表
- codevs 1835 魔法猪学院 A*寻k短路做了一个月卡死在spfa那了/(ㄒoㄒ)/~~
- 获得临时文件目录(Temp文件夹)
- 1057 - Collecting Gold (状态压缩DP)
- PowerShell_零基础自学课程_5_自定义PowerShell环境及Powershell中的基本概念
- juqery合成事件toggle方法
- centos 虚拟机桥接
- Mongodb_基本操作UCRD
- pycharm linux版快捷方式创建
- 解决ssh连接问题2
- 使用Java类加载SpringBoot、SpringCloud配置文件
- 未能写入输出文件“c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\2da42acc\ab2935
- pycharm如何在debug的时候动态执行python语句
- Android 进程保活招式大全(转载)
- cocos2d-x C++ iOS工程集成第三方支付宝支付功能
- C++基础知识:类的静态成员
热门文章
- CPP-基础:TCHAR
- Linux系统GEDIT编译运行C++
- kubernetes添加不了google apt-key
- Js自学学习-笔记6-8
- java在线聊天项目0.1版本 制作客户端窗体,使用swing(用户界面开发工具包)和awt(抽象窗口工具包)
- 674. Longest Continuous Increasing Subsequence@python
- linux 5.7.20和5.6.38版本 数据库忘记root密码怎么找回?
- 【Java基础】java中的反射机制与动态代理
- The twelve Day-前端之html
- raywenderlich.com Objective-C编码规范