题目:
给定两个字符串,一个模式串,一个目标串,找出目标串中符合模式串格式的字串
举例:str = "aaababaa", format = "XXYXY", 输出:"aabab"
思路: 将模式串按字符分类,存储每个字符出现的位置,例如:position['X'] = {0, 1, 3}。判断目标串中当前的子串是否符合模式串的格式。若符合,输出;否则,目标串中的指针向后移动一位,继续检查。分析:时间复杂度O(K*N),K是模式串的长度,N是目标串的长度
- #include <string>
- #include <map>
- #include <list>
- #include <stdio.h>
- /*
- * 字符串的模式匹配,类似正则表达式
- * 两个字符串:目标串和模式串
- * 打印目标串中具有模式串的模式的所有字串
- *
- */
- bool MatchCore(const std::string &,
- const std::map<char, std::list<size_t> > &,
- size_t);
- void StrMatch(const std::string & str,
- const std::string & format)
- {
- size_t fsize = format.size();
- if (fsize == 0 || fsize > str.size()) return;
- size_t start = 0;
- std::map<char, std::list<size_t> > position;
- for (size_t i = 0; i < fsize; ++ i)
- position[format.at(i)].push_back(i);
- while (start <= str.size() - fsize)
- {
- if (MatchCore(str, position, start))
- printf("%s\n", str.substr(start, fsize).c_str());
- ++ start;
- }
- }
- bool MatchCore(const std::string & str,
- const std::map<char, std::list<size_t> > & position,
- size_t start)
- {
- std::map<char, std::list<size_t> >::const_iterator miter = position.begin();
- for (; miter != position.end(); ++ miter)
- {
- std::list<size_t>::const_iterator liter = (miter->second).begin();
- size_t first = *liter + start;
- for (++ liter; liter != (miter->second).end(); ++ liter)
- {
- if (str.at(*liter + start) != str.at(first))
- return false;
- }
- }
- return true;
- }
PS:华为,2013,校招,面试
话外音:当时是华为的一面,在简单自我介绍后开始做题写代码。当时,第一次在面试官面前写代码,不免有点谨慎,生怕写的太乱。想了一会,开始写,当写到一半的时候,面试官不让我写了,估计他认为我用的时间超过了他认为这道题本该用的时间。我给他讲了下思路,还想让他注意到我考虑了边界等情况,他看了下代码,然后,说了句:你代码能力不是很好!我当时就受了打击。回来后来不断的回想,到底是哪里写的不入流,这么的不堪入目。
我想到了几点:
1、命名不是很规范,如len1,len2
2、出现了类似start += 5这样的易写难改的赋值,最好将常量赋给一个变量来管理,int size = 5; start += size;
3、解决问题的方式没有通用性,换一个模式串,就要修改代码
4、函数传递的参数没有想清楚,这在定义接口时,是致命的问题
细节中告诉别人的是写代码的素养,素养是靠代码的行数积累养成的,多写是前提但写前一定要三思。