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

    本题和之前的那道Isomorphic Strings比较类似,用hashmap来存储char-string对,代码如下:

     1 public class Solution {
     2     public boolean wordPattern(String pattern, String str) {
     3         String[] word = str.split(" ");
     4         Map<Character,String> map = new HashMap<Character,String>();
     5         if(pattern.length()!=word.length) return false;
     6         for(int i=0;i<pattern.length();i++){
     7             if(map.containsKey(pattern.charAt(i))){
     8                 if(!map.get(pattern.charAt(i)).equals(word[i])){
     9                     return false;
    10                 }
    11             }else{
    12                 if(map.containsValue(word[i])){
    13                     return false;
    14                 }
    15                 map.put(pattern.charAt(i),word[i]);
    16             }
    17         }
    18         return true;
    19     }
    20 }
  • 相关阅读:
    elasticsearch数据迁移
    Leetcode <剑指 Offer 64. 求1+2+…+n>
    Leetcode <27.移除元素>
    Leetcode <7.整数反转>
    Leetcode <1. 两数之和>
    python实现对于告警规则的判断思路
    Python实现密码生成器
    Autojs 打包APP+签名
    Docker 文档整理
    Pycharm 连接Linux远程开发
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6597792.html
Copyright © 2011-2022 走看看