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:

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.

分析:

这道题目的接口如果是string, vector会好做很多,但是他现有的接口是string, string,就需要用到istringstream

因为不能比较两边的长度,所以要在循环中和循环结束后两次判断,如果pattern比word长,或者word比pattern长,需要返回false。

解法:

class Solution {
public:
    bool wordPattern(string pattern, string str) {

        if (pattern.size() == 0 || str.size() == 0) {
            if (pattern.size() == str.size() ) {
                return true;
            }
            return false;
        }

        unordered_map<char, int> pattern2int;
        unordered_map<string, int> string2int;

        istringstream input(str);
        int i = 0;
        int n = pattern.size();

        for (string word; input>>word; i++) {
            if (i == n || pattern2int[pattern[i] ] != string2int[word]) {
                return false;
            }
            pattern2int[pattern[i] ] = i + 1;
            string2int[word] = i + 1;
        }

        if (i == n) {
            return true;
        }
        return false;
    }
};

results matching ""

    No results matching ""