首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模式匹配

模式匹配
EN

Code Review用户
提问于 2017-10-22 07:34:05
回答 2查看 654关注 0票数 2

我实现了一个简单的模式匹配算法。对优化有什么建议吗?

代码语言:javascript
复制
 #include<iostream>
 #include<string>

 int patten_search(const std::string &txt, const std::string &pat) {
     int found = 0;
     for (int i = 0; i<txt.size()-pat.size()+1; i++) {
         int lps = pat.size();
         for(int j=0; j<pat.size(); j++){
             if(pat[j] != txt[i+j])
                 lps --;
         }
         if(lps == pat.size()){
             i = i+lps;
             found = 1;
         }
     }
     return found;
 }


 int main() {
     std::string txt;
     std::string pat;
     std::cout<<"enter your text string"<<std::endl;
     std::cin>>txt;
     std::cout<<"enter your pattern which you would like to search"<<std::endl;
     std::cin>>pat;
     if(patten_search(txt, pat)){
         std::cout<<"Pattern found"<<std::endl;
     } else {
         std::cout<<"Pattern not found"<<std::endl;
     }
 }
EN

回答 2

Code Review用户

回答已采纳

发布于 2017-10-22 11:19:56

布尔答案:您的函数返回int,但它只返回01。在这里,bool更合适。

早期返回:一旦您找到“模式”,return。其他每一次事件都会保留found true,所以您只需快速退出即可。

早期中断:一旦您注意到某个字符不匹配,break。你不需要检查剩下的,比赛已经坏了。您也不需要计算匹配的字符数。一个布尔值就足够了。

如果我们应用这三种方法,我们最终会

代码语言:javascript
复制
bool patten_search(const std::string &txt, const std::string &pat) {    
    for (int i = 0; i < txt.size() - pat.size()+1; i++) {
        bool failed = false;
        for(int j = 0; j<pat.size(); j++){
            if(pat[j] != txt[i+j]) {
                failed = true;
                break;
            }
        }
        if(failed == false){
            return true;
        }
    }
    return false;
}

但是,除非您要获得最后一点的性能,否则最好使用标准库来发挥您的优势:

代码语言:javascript
复制
bool patten_search(const std::string &txt, const std::string &pat) {    
    return txt.find(pat) != std::string::npos;
}
票数 5
EN

Code Review用户

发布于 2017-10-22 23:20:54

您应该重命名该函数。当我阅读单词模式时,我会想到带有占位符的字符串,比如*.txt(\d+)-(\d+)-(\d+)。您的代码没有这样做,它只是搜索一个确切的字符串。函数名应该反映这一点。

这样做的一个好的副作用是,通过上面的重命名消除了错误的patten

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/178507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档