给定两个字符串,一个模式串,一个目标串,找出目标串中符合模式串格式的字串

来源:互联网 发布:sql insert into 日期 编辑:程序博客网 时间:2024/05/24 05:27
题目:给定两个字符串,一个模式串,一个目标串,找出目标串中符合模式串格式的字串

举例:str = "aaababaa", format = "XXYXY", 输出:"aabab"

思路:将模式串按字符分类,存储每个字符出现的位置,例如:position['X'] = {0, 1, 3}。判断目标串中当前的子串是否符合模式串的格式。若符合,输出;否则,目标串中的指针向后移动一位,继续检查。

分析:时间复杂度O(K*N),K是模式串的长度,N是目标串的长度


[cpp] view plaincopy
  1. #include <string>  
  2. #include <map>  
  3. #include <list>  
  4. #include <stdio.h>  
  5.   
  6. /* 
  7.  * 字符串的模式匹配,类似正则表达式 
  8.  * 两个字符串:目标串和模式串 
  9.  * 打印目标串中具有模式串的模式的所有字串 
  10.  *  
  11.  */  
  12. bool MatchCore(const std::string &,   
  13.                const std::map<char, std::list<size_t> > &,  
  14.                size_t);  
  15.   
  16. void StrMatch(const std::string & str,   
  17.               const std::string & format)  
  18. {  
  19.     size_t fsize = format.size();  
  20.     if (fsize == 0 || fsize > str.size()) return;  
  21.   
  22.     size_t start = 0;  
  23.   
  24.     std::map<char, std::list<size_t> > position;  
  25.     for (size_t i = 0; i < fsize; ++ i)  
  26.         position[format.at(i)].push_back(i);          
  27.   
  28.     while (start <= str.size() - fsize)  
  29.     {  
  30.         if (MatchCore(str, position, start))  
  31.             printf("%s\n", str.substr(start, fsize).c_str());  
  32.         ++ start;  
  33.     }  
  34. }  
  35.   
  36. bool MatchCore(const std::string & str,   
  37.                const std::map<char, std::list<size_t> > & position,   
  38.                size_t start)  
  39. {  
  40.     std::map<char, std::list<size_t> >::const_iterator miter = position.begin();  
  41.     for (; miter != position.end(); ++ miter)  
  42.     {  
  43.         std::list<size_t>::const_iterator liter = (miter->second).begin();  
  44.         size_t first = *liter + start;  
  45.         for (++ liter; liter != (miter->second).end(); ++ liter)  
  46.         {  
  47.             if (str.at(*liter + start) != str.at(first))  
  48.                 return false;  
  49.         }  
  50.     }  
  51.     return true;  
  52. }  


PS:华为,2013,校招,面试

话外音:当时是华为的一面,在简单自我介绍后开始做题写代码。当时,第一次在面试官面前写代码,不免有点谨慎,生怕写的太乱。想了一会,开始写,当写到一半的时候,面试官不让我写了,估计他认为我用的时间超过了他认为这道题本该用的时间。我给他讲了下思路,还想让他注意到我考虑了边界等情况,他看了下代码,然后,说了句:你代码能力不是很好!我当时就受了打击。回来后来不断的回想,到底是哪里写的不入流,这么的不堪入目。

我想到了几点:

1、命名不是很规范,如len1,len2

2、出现了类似start += 5这样的易写难改的赋值,最好将常量赋给一个变量来管理,int size = 5; start += size;

3、解决问题的方式没有通用性,换一个模式串,就要修改代码

4、函数传递的参数没有想清楚,这在定义接口时,是致命的问题

细节中告诉别人的是写代码的素养,素养是靠代码的行数积累养成的,多写是前提但写前一定要三思。


0 0
原创粉丝点击