zoukankan      html  css  js  c++  java
  • [LeetCode290]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.

    思路:考察的是字符串模式匹配,可以用map来解决,先将str分割放到一个vector<string>中,再将pattern分割一起放入map<char,string>中,遍历判断是否是对应的键或值即可。

    代码:

    class Solution {
    public:
        bool wordPattern(string pattern, string str) {
            stringstream ss(str);
            string s;
            vector<string> strVec;
            while(ss >> s)
            {   
             strVec.push_back(s);
            }
    
            if(strVec.size() != pattern.size())
            return false;
            map<char, string> hash;
            int i = 0;
            for(auto c : pattern)
            {
                if(hash.count(c))
                {
                    if(hash[c] != strVec[i])
                        return false;
                }
                else
                {
                    for(auto p : hash)
                    {
                        if(p.second == strVec[i])
                            return false;
                    }
                    hash[c] = strVec[i];
                }
                ++i;
            }
            return true;
        }
    };
  • 相关阅读:
    python网站开发准备ubuntu14.04安装mysql实现windows管理
    python 数据结构之二叉树
    python 数据结构之二分查找的递归和普通实现
    python 数据结构之归并排序
    python数据结构之希尔排序
    ctf study of jarvisoj reverse
    python数据结构之quick_sort
    堆与栈
    汇编整理
    js运算符
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5188201.html
Copyright © 2011-2022 走看看