1. 程式人生 > >字串萬用字元/華為機試(C/C++)

字串萬用字元/華為機試(C/C++)

題目描述

問題描述:在計算機中,萬用字元一種特殊語法,廣泛應用於檔案搜尋、資料庫、正則表示式等領域。現要求各位實現字串萬用字元的演算法。 要求: 實現如下2個萬用字元: *:匹配0個或以上的字元(字元由英文字母和數字0-9組成,不區分大小寫。下同) ?:匹配1個字元

輸入: 萬用字元表示式; 一組字串。

輸出: 返回匹配的結果,正確輸出true,錯誤輸出false

輸入描述:

先輸入一個帶有萬用字元的字串,再輸入一個需要匹配的字串

輸出描述:

返回匹配的結果,正確輸出true,錯誤輸出false

示例1

輸入

te?t*.*
txt12.xls

輸出

false

程式碼:借用

//第六十九題  字串萬用字元
#include<string>
#include<iostream>
#include<vector>
using namespace std;
int match_string(string m_str, string w_str) //match wildcard 萬用字元
{
	int m_len = m_str.size();
	int w_len = w_str.size();
	vector<vector<int> > b_dp(w_len + 1, vector<int>(m_len + 1, 0));
	//多加一行一列作為初始初值所用
	b_dp[0][0] = 1;
	for (int i = 1; i <= w_len; i++)
	{
		char ch = w_str[i - 1];
		////設定每次迴圈的初值,即當星號不出現在首位時,匹配字串的初值都為false
		b_dp[i][0] = b_dp[i - 1][0] && (ch == '*');
		for (int j = 1; j <= m_len; j++)
		{
			char ch2 = m_str[j - 1];
			if (ch == '*')
				b_dp[i][j] = b_dp[i - 1][j] || b_dp[i][j - 1]; //當匹配字元為*號時,狀態取決於上面狀態和左邊狀態的值
			else
				b_dp[i][j] = b_dp[i - 1][j - 1] && (ch == '?' || ch2 == ch);//決定於上一次和本次
		}
	}
	return b_dp[w_len][m_len];
}
int main()
{
	string str1, str2;
	while (cin >> str1 >> str2)
	{
		int rst = match_string(str2, str1);
		if (rst == 1)
			cout << "true" << endl;
		else
			cout << "false" << endl;
	}
}