设为首页 加入收藏

TOP

[LeetCode] Implement strstr() to Find a Substring in a String
2014-11-23 21:54:15 来源: 作者: 【 】 浏览:10
Tags:LeetCode Implement strstr Find Substring String
思路:其实就是逐个匹配,解法没什么亮点,我也不想说什么。当然也可以把IsMatch嵌入到StrStr里面,可以减少函数调用的开销,但是可读性可能就会降低了。
1、当前字符匹配,则返回当前字符。
2、当前字符不匹配,则往前跳一个。
其实和A String Replace Problem 类似的思想,核心参考代码:
bool IsMatch(const char *Str, const char *Pattern)  
{  
    assert(Str && Pattern);  
    while(*Pattern != '\0')  
    {  
        if(*Str++ != *Pattern++)  
        {  
            return false;  
        }  
    }  
    return true;  
}  
  
char* StrStr(const char *Str, const char *Pattern)  
{  
    assert(Str && Pattern);  
    while(*Str != '\0')  
    {  
        if(IsMatch(Str, Pattern))  
        {  
            return const_cast(Str);  
        }  
        else  
        {  
            ++Str;  
        }  
    }  
    return NULL;  
}  

照旧,给出main函数的调用:
#include  
#include  
int main()  
{  
    const int MAX_N = 50;  
    char Str[MAX_N];  
    char Pattern[MAX_N];  
    char* Ans = NULL;  
    while(gets(Str) && gets(Pattern))  
    {  
        Ans = StrStr(Str, Pattern);  
        if(Ans)  
        {  
            puts(Ans);  
        }  
        else  
        {  
            printf("不是子串\n");  
        }  
    }  

return 1;
}
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇cp命令的编写――浅谈系统调用 下一篇HDU 3328 Flipper (stack)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis压力测试实战 - (2025-12-27 09:20:24)
·高并发一上来,微服 (2025-12-27 09:20:21)
·Redis 高可用架构深 (2025-12-27 09:20:18)
·Linux 系统监控 的完 (2025-12-27 08:52:29)
·一口气总结,25 个 L (2025-12-27 08:52:27)