Word Pattern
Total Accepted: 18003 Total Submissions: 66490 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.
class Solution { public: bool wordPattern(string pattern, string str) { unordered_map<char,string> c_str_map; unordered_map<string,char> str_c_map; istringstream iss(str); string word; int i=0; while(i<pattern.size() && iss>>word ){ char c = pattern[i++]; if(i==0){ c_str_map[c] = word; str_c_map[word] = c; }else{ string map_str = c_str_map[c]; char map_c = str_c_map[word]; if(map_str == "" && map_c=='\0'){ c_str_map[c] = word; str_c_map[word] = c; }else if(map_str!=word || map_c!=c){ return false; } } } if(i==pattern.size() && iss.eof()){ return true; } return false; } }; /* "a" "" "a" "word" "a" "word word" "ab" "word" "ab" "word word" "ab" "word sek" "aba" "word sek word" */
写者:zengzy
出处: http://www.cnblogs.com/zengzy
标题有【转】字样的文章从别的地方转过来的,否则为个人学习笔记
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号