[LeetCode]28.Implement strStr()

简介:

【题目】

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

【题意】

实现strStr()功能。

【分析】

暴力算法代码如下。更高效的的算法有 KMP 算法、Boyer-Mooer 算法和Rabin-Karp 算法。面试中暴力算法足够了。

具体参考:KMP字符串模式匹配详解

【代码】

/*********************************
*   日期:2014-02-02
*   作者:SJF0115
*   题号: Implement strStr()
*   来源:http://oj.leetcode.com/problems/implement-strstr/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;


class Solution {
public:
    char* strStr(char *haystack, char *needle) {
        if(needle == NULL || haystack == NULL){
            return NULL;
        }
        int offset;
        int m = strlen(haystack);
        int n = strlen(needle);
        for(int i = 0;i < m - n + 1;i++){
            for(offset = 0;offset < n;){
                if(haystack[i+offset] == needle[offset]){
                    offset++;
                }
                else{
                    break;
                }
            }
            if(offset == n){
                return haystack+i;
            }
        }
        return NULL;
    }
};

int main() {
    Solution solution;
    char *haystack = "abcedf";
    char *needle = "edf";
    char *str = solution.strStr(haystack,needle);
    cout<<str<<endl;
    return 0;
}


目录
相关文章
|
算法 C++ 索引
leetcode-28:实现 strStr()(字符串匹配,暴力匹配算法和KMP算法)
leetcode-28:实现 strStr()(字符串匹配,暴力匹配算法和KMP算法)
165 0
|
12月前
【LeetCode 21】28. 实现 strStr()
【LeetCode 21】28. 实现 strStr()
80 0
|
SQL 算法 数据可视化
Leetcode第28题:实现 strStr()【python】
Leetcode第28题:实现 strStr()【python】
LeetCode-28 实现strStr() KMP算法的学习
LeetCode-28 实现strStr() KMP算法的学习
|
算法 安全 Java
LeetCode - #28 实现 strStr()
不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。如果大家有建议和意见欢迎在文末留言,我们会尽力满足大家的需求。
180 0
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
135 0
leetcode 28 找出字符串第一个匹配的下标(KMP实现strStr)
|
算法 Java C语言
leetcode:28.实现strStr()
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
119 0
|
存储 前端开发 算法
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
281 0
一行代码解决LeetCode实现 strStr()使用JavaScript解题|前端学算法
|
存储
LeetCode 232. Implement Queue using Stacks
使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 peek() -- 返回队列首部的元素。 empty() -- 返回队列是否为空。
118 0
LeetCode 232. Implement Queue using Stacks
LeetCode 225. Implement Stack using Queues
使用队列实现栈的下列操作: push(x) -- 元素 x 入栈; pop() -- 移除栈顶元素; top() -- 获取栈顶元素; empty() -- 返回栈是否为空
136 0
LeetCode 225. Implement Stack using Queues

热门文章

最新文章

下一篇
日志分析软件