长沙建网站需要多少钱,百度竞价开户渠道,汽车之家网页版官网找车,高端网吧电脑配置题目描述
给定一种规律 pattern 和一个字符串 s #xff0c;判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配#xff0c;例如#xff0c; pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。 提示:
1 pattern.length 300
pa…题目描述
给定一种规律 pattern 和一个字符串 s 判断 s 是否遵循相同的规律。
这里的 遵循 指完全匹配例如 pattern 里的每个字母和字符串 s 中的每个非空单词之间存在着双向连接的对应规律。 提示:
1 pattern.length 300
pattern 只包含小写英文字母
1 s.length 3000
s 只包含小写英文字母和
s 不包含 任何前导或尾随对空格
s 中每个单词都被 单个空格 分隔题目分析
首先判断pattern串的长度与s串的单词数是否相等如果不相等那么这两个字符串的模式必然不一样如果相等了在继续进行下一项的判断因为总共有26个小写字母所以我们可以利用字母的值为串的下标将单词存储起来如果字母一样就检查当前单词是否出现过如果没有出现过记录下来此单词如果已经出现过了那么就将当前单词与已出现的单词作比较如果相同那么目前的模式仍然一样。依次比对下去即可。
代码
bool wordPattern(char* pattern, char* s) {char *x[26];for(int i0; i26; i){x[i] NULL;}int pattern_length 0;while(pattern[pattern_length]!\0);pattern_length--;int k 0;int count 0;for(;s[k]!\0; k){if(s[k] ){count;}}if(k!0){count;}if(count!pattern_length){return false;}int i0; int j0;for(i0; pattern[i]!\0; i){int length_word 0;if(x[pattern[i]-a]NULL){while(s[jlength_word]! s[jlength_word]!\0){length_word;}x[pattern[i]-a] (char *)malloc(sizeof(char)*(length_word1));for(int k0; klength_word; k){x[pattern[i]-a][k] s[jk];}x[pattern[i]-a][length_word] \0;j j length_word1; }else{char *y NULL;while(s[jlength_word]! s[jlength_word]!\0){length_word;}y (char *)malloc(sizeof(char)*(length_word1));for(int k0; klength_word; k){y[k] s[jk];}y[length_word] \0;j j length_word1;if(strcmp(x[pattern[i]-a], y)){return false;}}}for(int i0; i26; i){for(int ji1; j26; j){if(x[i]!NULLx[j]!NULL){if(!strcmp(x[i], x[j])){return false;}}}}return true;
}提交结果截图