leetcode 哈希表专题-Word Pattern
2015-10-17 10:39
375 查看
原文链接:https://leetcode.com/problems/word-pattern/
原文题目:
我用的是C语言的实现方法:
原文题目:
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; }
相关文章推荐
- 客户端给服务端发送文本。服务端将文本转成大写在返回给客户端
- 评论
- configure 时-g 与 -O0 开关控制
- FineReport——JS二次开发(隐藏下拉框控件的倒三角)
- Android 多线程 和异步的实践:跳转,同步显示时间,倒计时的实现,知识点
- I2C SPI UART和CAN的区别
- clone
- coco2d-x 游戏背景音乐的添加
- java.sql.SQLException: ORA-00911: 无效字符 解决方案
- 搜索引擎的搜索技巧——如何利用浏览器精准搜索(科普文)
- 浅析修改、删除数据后刷新JTable的方法
- 使用循环的方式打印字符串所有排列组合
- jsoup 简介
- 即时通信方法、系统、装置和即时通信终端
- 循环冗余校验CRC总结
- jQuery第二课 ——节点选择、元素创建与操作、包装对象、jq转原生js
- 【CSS】兼容IE7的各个各样的标题面板
- 浅谈Java虚拟机的工作模式Client和Server。
- Delphi RenameFile 文件改名
- hdoj 1845 Jimmy’s Assignment 【HK】