leetcode 哈希表专题-Word Pattern

来源:互联网 发布:域名云解析有什么用 编辑:程序博客网 时间:2024/05/22 10:37

原文链接:https://leetcode.com/problems/word-pattern/

原文题目:

Given a pattern and a string str, find if str follows the same pattern.Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.Examples:pattern = "abba", str = "dog cat cat dog" should return true.pattern = "abba", str = "dog cat cat fish" should return false.pattern = "aaaa", str = "dog cat cat dog" should return false.pattern = "abba", str = "dog dog dog dog" should return false.Notes:You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.Credits:Special thanks to @minglotus6 for adding this problem and creating all test cases.

我用的是C语言的实现方法:

bool wordPattern(char* pattern, char* str) {    int temp[26] = {0};    if(pattern == NULL || str == NULL || *pattern == '\0' || *str == '\0')        return false;    for(int i = 0 ; i < 26 ;  i++ )    {           temp[i] = -1;    }    int i = 0;    int strLength = 0;    char * saveOfIp[26];//新建一个指针数组    int inset = 0;    while(*(pattern + i) != '\0')    {        if(strLength != 0)        {            if(*(str + strLength -1 )  == '\0')               return false;        }        int weight = 0;        while(*(str +strLength + weight) != ' ' &&  *(str +strLength + weight) != '\0')        {             weight ++;        }        char *saveChars = (char *)malloc(weight + 1);        if(saveChars == NULL)           printf("error in the malloc");       if( memcpy(saveChars,str+strLength,weight) == NULL)            printf("error in the memcpy");        strLength = strLength + ( weight + 1 );        *(saveChars + weight ) = '\0';//字符串要加结尾        char *every;        char everyTemp;        everyTemp = *(pattern +i) - 'a';//提取出每次的pattern一个字符用以比较        if(temp[everyTemp] == -1)        {            int j = 0;             while(j<26 )            {                if(temp[j] == -1)                {                       j++;                       continue;                }                if(strcmp(saveOfIp[j],saveChars) == 0)                    return false;                j++;            }            temp[everyTemp] = 1;//将结果存在哈希表里            saveOfIp[everyTemp] = (char *)malloc(weight +1);//字符串要加结尾,所以要weight+1             memcpy(saveOfIp[everyTemp],saveChars,weight + 1);//复制进一个数组保存        }        else        {            if(strcmp(saveOfIp[everyTemp],saveChars) != 0)                return false;        }        i++;    }    if(*(str + strLength - 1)  != '\0')        return false;    return true;}
0 0
原创粉丝点击