예제 #1
0
bool wordPattern(string &pattern, int i, string &str, int j, unordered_map<char,string>& myMap, unordered_set<string>& mySet){
	if(i == pattern.length() && j == str.length()) return true;
	if(i == pattern.length() || j == str.length()) return false;

	char patCur = pattern[i];
	if(myMap.find(patCur) != myMap.end()) {
		string strCur = myMap[patCur];

        int pos = strCur.length();
        if(strCur != str.substr(j,pos))
            return false;
            
		return wordPattern(pattern,i+1,str,j+pos,myMap,mySet);
	}

	for(int pos = j; pos < str.length(); pos++) {
		string strCur = str.substr(j, pos-j+1);
		if(mySet.find(strCur) != mySet.end())
			continue;
		myMap[patCur] = strCur;
		mySet.insert(strCur);

		if(wordPattern(pattern, i+1, str, pos+1, myMap, mySet))
			return true;
		myMap.erase(patCur);
		mySet.erase(strCur);
	}

	return false;
	 
}
static void test1(void)
{
    bool c;
    char pattern[] = "abba";
    char str[] = "dog cat cat dog";
    c = wordPattern(pattern, str);
    printf("%s\n", (c)? "true": "false");
}
static void test5(void)
{
    bool c;
    char pattern[] = "hut";
    char str[] = "pig cat dog";
    c = wordPattern(pattern, str);
    printf("%s\n", (c)? "true": "false");
}
예제 #4
0
int
main()
{
    int res = -1;
    while (scanf("%s", pt) != EOF) {
        getchar();
        gets(st);
        printf("pattern: %s\n", pt);
        printf("str: %s\n", st);
        res = wordPattern(pt, st);
        printf("res = %d\n", res);
    }
    return 0;
}
예제 #5
0
int main(void)
{
	char pattern[] = "adda";
	char str[] = "dog cat cat dog";

	printf("pattern:%s\n", pattern);
	printf("str:%s\n", str);

	bool result = wordPattern(pattern, str);
	if (result)
		printf("Yes!\n");
	else
		printf("No!\n");

	return 0;
}
예제 #6
0
int main()
{
    char pattern[10];
    char str[1000];
    int ret_val = 0;

    memset(pattern,'\0',sizeof(pattern));
    memset(str,'\0',sizeof(str));
    printf("Enter the pattern:");
    //fgets(pattern,sizeof(pattern),stdin);
    gets(pattern);
    printf("Enter the string:");
    //fgets(str,sizeof(str),stdin);
    gets(str);
    ret_val = wordPattern(pattern,str);

    if(ret_val) {
        printf("string matches with pattern\n");
    } else {
        printf("string doesn't match with pattern\n");
    }
    return 0;
}
예제 #7
0
#include "Catch/single_include/catch.hpp"

#include "WordPattern.hpp"

TEST_CASE("WordPattern") {
	REQUIRE(wordPattern("abba", "dog cat cat dog") == true);
	REQUIRE(wordPattern("abba", "dog cat cat fish") == false);
	REQUIRE(wordPattern("aaaa", "dog cat cat dog") == false);
	REQUIRE(wordPattern("abba", "dog dog dog dog") == false);
}
예제 #8
0
bool wordPatternMatch(string pattern, string str) {
	unordered_map<char,string> myMap;
	unordered_set<string> mySet;

	return wordPattern(pattern,0,str,0,myMap,mySet);
예제 #9
0
void main(void)
{
    bool b;
    b = wordPattern("abba", "dog cat cat dog");
    b = wordPattern("abbc", "dog cat cat dog");
}