算法代码带有通配符的字符串和另一个字符串进行匹配

文章结束给大家来个程序员笑话:[M]

    先吐个槽吧,公司也有这个算法,看了半天也不知道干什么呢,写的非常复杂,偶尔的发明一个算法,巧小而精细,上面具体述叙:

    * 可以配匹0个或0个以上的字符

    ?可以配匹一个字符

    

    这个算法应用的是递归的算法,开始心担如果字符串长过的话,会因递归起引栈的溢出,还好在网上查了一下,win32默许的递归栈巨细是2M,这足以行进很长字符串的配匹。

    上面是心核的代码,路思都在代码的注释中,上面给出代码:

    

    每日一道理
成功的花朵开放在啊勤劳的枝头,失败的苦果孕育在懒惰的温床之中。
#include<iostream>
#include<string>
using namespace std;

bool match(char *pattern, char *content) {
	// if we reatch both end of two string, we are done
	if ('\0' == *pattern && '\0' == *content)
		return true;
	/* make sure that the characters after '*' are present in second string.
      this function assumes that the first string will not contain two
       consecutive '*'*/
	if ('*' == *pattern && '\0' != *(pattern + 1) && '\0' == *content)
		return false;
	// if the first string contains '?', or current characters of both 
    // strings match
	if ('?' == *pattern || *pattern == *content)
		return match(pattern + 1, content + 1);
	/* if there is *, then there are two possibilities
       a) We consider current character of second string
       b) We ignore current character of second string.*/
	if ('*' == *pattern)
		return match(pattern + 1, content) || match(pattern, content + 1);
	return false;
}

void test(char *pattern, char *content) {
	if (NULL == pattern || NULL == content)
		puts("no");
	match(pattern, content) ? puts("yes") : puts("no");
}

int main(int argc, char *argv[]) {
	test("g*ks", "geeks"); // Yes
    test("ge?ks*", "geeksforgeeks"); // Yes
    test("g*k", "gee");  // No because 'k' is not in second
    test("*pqrs", "pqrst"); // No because 't' is not in first
    test("abc*bcd", "abcdhghgbcd"); // Yes
    test("abc*c?d", "abcd"); // No because second must have 2 instances of 'c'
    test("*c*d", "abcd"); // Yes
    test("*?c*d", "abcd"); // Yes
	cin.get();
    return 0;
}

文章结束给大家分享下程序员的一些笑话语录: 某程序员对书法十分感兴趣,退休后决定在这方面有所建树。花重金购买了上等的文房四宝。一日突生雅兴,一番磨墨拟纸,并点上了上好的檀香,颇有王羲之风 范,又具颜真卿气势,定神片刻,泼墨挥毫,郑重地写下一行字:hello world.

posted @ 2013-05-09 20:43  xinyuyuanm  阅读(385)  评论(0编辑  收藏  举报