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


    题目标签:Hash Table

      题目给了我们一个pattern 和一个 str, 让我们判断,str 是否和 pattern 一致。

      首先,把str split 到 words array 里,如果pattern 的长度 和 words 长度 不一样,直接返回false;

      接下来利用HashMap,把pattern 里的 char 当作key, 每一个word 当作value 存入,如果遇到一样的char,但是有着不一样的value,返回false;如果遇到不一样的char,但有着一样的value,返回false;最后遍历完之后,返回true。

    Java Solution:

    Runtime beats 36.87% 

    完成日期:06/05/2017

    关键词:HashMap

    关键点:char 当作 key,word 当作 value

     1 class Solution 
     2 {
     3     public boolean wordPattern(String pattern, String str) 
     4     {
     5         HashMap<Character, String> map = new HashMap<>();
     6         
     7         String[] words = str.split(" ");
     8         
     9         if(pattern.length() != words.length)
    10             return false;
    11         
    12         for(int i=0; i<pattern.length(); i++)
    13         {
    14             char c = pattern.charAt(i);
    15 
    16             if(map.containsKey(c))
    17             {
    18                 if(!map.get(c).equals(words[i]))
    19                     return false;
    20             }
    21             else
    22             {
    23                 if(map.containsValue(words[i]))
    24                     return false;
    25                 
    26                 map.put(c, words[i]);
    27             }
    28         }
    29         
    30         return true;
    31     }
    32 }

    参考资料:N/A

    LeetCode 题目列表 - LeetCode Questions List

  • 相关阅读:
    Git 基础
    SharePoint 2013 对象模型操作"网站设置"菜单
    SharePoint 2013 隐藏部分Ribbon菜单
    SharePoint 2013 Designer系列之数据视图筛选
    SharePoint 2013 Designer系列之数据视图
    SharePoint 2013 Designer系列之自定义列表表单
    SharePoint 2013 设置自定义布局页
    SharePoint 2013 "通知我"功能简介
    SharePoint 2013 创建web应用程序报错"This page can’t be displayed"
    SharePoint 禁用本地回环的两个方法
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7791491.html
Copyright © 2011-2022 走看看