LeetCode 290. Word Pattern

来源:互联网 发布:iphone连mac充电好吗 编辑:程序博客网 时间:2024/06/17 03:58

290. 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:

  1. pattern = "abba", str = "dog cat cat dog" should return true.
  2. pattern = "abba", str = "dog cat cat fish" should return false.
  3. pattern = "aaaa", str = "dog cat cat dog" should return false.
  4. 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.


/*题意:给定一个pattern, 和一个单词组成的字符串,以空格隔开看单词排列的规律是否跟pattern一致。*/class Solution {public:    bool wordPattern(string pattern, string str) {        vector<string>wordlist;        string word;        istringstream stream(str);        vector<int>nums(26,0);        for(int i = 0; i < pattern.length(); i++)            nums[pattern[i]-'a']++;        int sum = 0;        for(int i = 0; i < 26; i++)//统计pattern中不同字母的个数            if(nums[i])sum++;        while(stream>>word){//将字符串切分成单词            wordlist.push_back(word);        }        if(pattern.length() == wordlist.size()){            for(int i = 0; i < pattern.length()-1; i++)                for(int j = i + 1; j < pattern.length(); j++){                    if(pattern[i] == pattern[j])                        if(wordlist[i] != wordlist[j])                            return false;                }            sort(wordlist.begin(),wordlist.end());            int k = 1;            for(int j = 1; j < wordlist.size(); j++)                if(wordlist[j] != wordlist[j-1])k++;            if(sum == k)                return true;            else                 return false;        }else{            return false;        }    }};