290. Word Pattern
- Total Accepted: 45113
- Total Submissions: 148465
- Difficulty: Easy
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.
Subscribe to see which companies asked this question
题意:给定模式 pattern "dffdg" ,给定包含单词的字符串str:“dog cat cat dog finish”
如果pattern中的相同字符对应的str中的单词是相同的,并且pattern中不同的字符对应str中的单词是不一样的,那么就返回true,否则返回false。
下面代码比较繁琐,先贴着容易理解:
1 bool wordPattern(char* pattern, char* str) { 2 int size = strlen(pattern); 3 int str_index[size];//存储字符串中单词的位置 4 int i,j; 5 char *p = str; 6 int str_len1; 7 int str_len2; 8 i = 0; 9 j = 1; 10 str_index[0] = i; 11 /** 12 * 1. 分割字符串中单词,并存储 13 * 2. 取货字符串中单词个数与pattern中的字符个数,不等直接false 14 * 3. 针对pattern中每个字符,比较对应的str中单词是否相等 15 */ 16 17 18 //取出str中的每个单词,并存储起来 19 while(*p != '\0'){ 20 if(*p == ' '){ 21 str_index[j++] = i + 1;//多个空格 22 } 23 i++;//记录指针移动的位置 24 ++p;//字符串指针移动 25 } 26 27 //单词个数和字符的个数不相等,直接认为false 28 if(size != j) 29 return false; 30 31 p = pattern; 32 i = 0; 33 while(i < size){ 34 //针对每一个字符比较对应的单词是否相等 35 for(j = 0;j < size; j++){ 36 //pattern相等时候的字符串中的单词应该对应相等 37 if(pattern[i] == pattern[j]){ 38 //判断是不是最后一个字符 因为后面使用了i+1容易越界 39 if(i != size-1) 40 if(strncmp(str+str_index[i],str+str_index[j],str_index[i+1] - str_index[i] -1) != 0) 41 return false; 42 else if(i == size-1 && i != j) 43 if(strncmp(str+str_index[i],str+str_index[j],str_index[j+1] - str_index[j] -1) != 0) 44 return false; 45 }else{ 46 //当字符不相等的时候还需要比较两个字符对应的单词不相等 47 //判断是不是最后一个字符 因为后面使用了i+1容易越界 48 if(i != size-1){ 49 //为strncpy 函数做准备,因为可能 a 和 b分别对应单词 g 和 good.如果只比较前一个单词那么就出错了 50 str_len1 = str_index[i+1] - str_index[i] -1; 51 str_len2 = str_index[j+1] - str_index[j] -1; 52 if(str_len1 == str_len2) 53 if(strncmp(str+str_index[i],str+str_index[j],str_index[i+1] - str_index[i] -1) == 0) 54 return false; 55 } 56 else if(i == size-1 && i != j) 57 //为strncpy 函数做准备,因为可能 a 和 b分别对应单词 g 和 good.如果只比较前一个单词那么就出错了 58 str_len1 = strlen(str) - str_index[i]; 59 str_len2 = str_index[j+1] - str_index[j] -1; 60 if(str_len1 == str_len2) 61 if(strncmp(str+str_index[i],str+str_index[j],str_index[j+1] - str_index[j] -1) == 0) 62 return false; 63 } 64 65 } 66 i++; 67 } 68 return true; 69 }