当前位置:编程学习 > C/C++ >>

[LeetCode] Implement strstr() to Find a Substring in a 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<char *>(Str);  
        }  
        else  
        {  
            ++Str;  
        }  
    }  
    return NULL;  
}  

 

 
照旧,给出main函数的调用:
 
 
#include<stdio.h>  
#include<assert.h>  
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;  
}  
 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,