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
- leetcode 哈希表专题-Word Pattern
- LeetCode Word Pattern 哈希表
- leetcode 290. Word Pattern-单词模式|哈希表
- leetcode | Word Pattern
- 【leetcode】290. Word Pattern
- leetcode 290: Word Pattern
- [Leetcode]Word Pattern
- [leetcode 290]Word Pattern
- LeetCode 290 Word Pattern
- 【leetcode】290. Word Pattern
- [LeetCode 290] Word Pattern
- leetcode 290 Word Pattern
- LeetCode 2 Word Pattern
- leetcode word-pattern
- leetcode: Word Pattern
- leetcode:Word Pattern
- [Leetcode]Word Pattern
- LeetCode Word Pattern
- 第七周项目4-队列数组
- 客户端给服务端发送文本。服务端将文本转成大写在返回给客户端
- Nginx部署时发现的问题
- [leetcode] Swap Nodes in Pairs
- assert()断言函数以及NODEBUG用法总结
- leetcode 哈希表专题-Word Pattern
- Python 代码调试技巧
- 1005. 继续(3n+1)猜想 (25)
- Android 动画效果弹出PopupWindow,同时屏幕背景变暗
- 选择排序
- HBase 中存储结构
- SQL FOREIGN KEY 约束 高级教程
- c++的传递的二进制流进行文件上传操作
- BSD GPL Apache 开源协议