zoukankan      html  css  js  c++  java
  • 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记录是否pattern和str匹配。

    注意,map的键值这里不能为0,因为为0时map默认是访问了未创建过的键,因此要从1开始。

    此外,for循环里真的可以实现很多东西,用好了会让代码很精简。

     1 class Solution {
     2 public:
     3     bool wordPattern(string pattern, string str) {
     4         map<char, int> dict1;
     5         map<string, int> dict2;
     6         stringstream ss(str);
     7         int i = 0, n = pattern.size();
     8         for (string word; ss >> word; i++)
     9         {
    10             if (i == n || dict1[pattern[i]] != dict2[word])
    11                 return false;
    12             dict1[pattern[i]] = dict2[word] = i + 1;
    13         }
    14         return i == n;
    15     }
    16 };
  • 相关阅读:
    C#产生不重复随机数
    NT6 HDD Installer(硬盘装系统工具)装系统
    R语言实现 广义加性模型 Generalized Additive Models(GAM) 入门
    matlab小段代码学习
    java连接sql server2005
    python正则表达式
    Ubuntu下安装配置JDK 7
    mysql取代rand()的高效率随机读取方法
    UVA 1335 Beijing Guards
    杂思
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4908181.html
Copyright © 2011-2022 走看看