請實現一個函數用來匹配包括'.'和'*'的正則表達式。模式中的字符'.'表示任意一個字符,而'*'表示它前面的字符可以出現任意次(包含0次)。 在本題中,匹配是指字符串的所有字符匹配整個模式。例如,字符串"aaa"與模式"a.a"和"ab*ac*a"匹配,但是與"aa.a"和"ab*a"均不匹配


// test20.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<cstring>
#include<string.h>
#include<deque>
#include <forward_list>

using namespace std;

//關於能否匹配可用遞歸的方式實現
//匹配上的情況
   
   //1.下一位是*,分三種情況:
  //1.1 matchCore(str+1,pattern) 模式串匹配成功,並嘗試匹配下一字符

  //1.3 matchCore(str,pattern+2) 模式串未匹配
  //2.下一位不是*,則pattern對應為應該與str相等或者pattern的對應為為.
  //matchCore(str+1, pattern + 1)
  //3.對應為不匹配,返回false
class Solution {
public:
	bool match(char* str, char* pattern)
	{
		if (str == NULL || pattern == NULL)
			return false;
		return matchCore(str,pattern);
	}
	bool matchCore(char* str, char* pattern)
	{
		if (*str == '\0'&&*pattern == '\0') return true; //迭代終止條件
		if (*str != '\0'&&*pattern == '\0') return false;//迭代終止條件
		if (*(pattern + 1) == '*')
		{
			if (*str == *pattern||(*pattern=='.'&&*str!='\0'))
				return matchCore(str + 1, pattern) || matchCore(str, pattern + 2);
			else
				return matchCore(str, pattern + 2);
		}
		if (*str == *pattern || (*pattern=='.'&&*str!='\0'))
			return matchCore(str+1,pattern+1);
		
		return false;
	}
};
int main()
{

 
	Solution so;
	char* str = "aaa";
	//char* pattern1 = "a*";
//	cout << "str的長度是:" << strlen(str) << endl;
	char* pattern1 = "ab*a*c*a";
	char* pattern2 = "a.a";
	char* pattern3 = "ab*a";
	char* pattern4 = "aa.a";
	char* pattern5 = "bbbba";
	char* pattern6 = ".*a*a";
	/*char* str = "aaa";
	char* pattern1 = "bbbba";*/
	//char* pattern1 = "";
	//
	cout << "pattern1 匹配的結果是: " << so.match(str, pattern1) <<endl;
	cout << "pattern2 匹配的結果是: " << so.match(str, pattern2) << endl;
	cout << "pattern3 匹配的結果是: " << so.match(str, pattern3) << endl;
	cout << "pattern4 匹配的結果是: " << so.match(str, pattern4) << endl;
	cout << "pattern5 匹配的結果是: " << so.match(pattern5, pattern6) << endl;
	return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM