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.

    题目含义:给定一个模式,判断句子中的单词是否满足模式?

     1     public boolean wordPattern(String pattern, String str) {
     2         if(str.split(" ").length != pattern.length()) return false;
     3         Map<Character,String> map = new HashMap<>(pattern.length());//维护pattern字符与后面字符串的映射关系
     4         Map<String,Boolean> valueMap = new HashMap<>();
     5         
     6         char p_arra[] = pattern.toCharArray();
     7         String str_arra[] = str.split(" ");
     8         int index=0;
     9         while (index<p_arra.length)
    10         {
    11             if (!map.containsKey(p_arra[index]))
    12             {
    13                 if (valueMap.containsKey(str_arra[index])) return false;
    14                 map.put(p_arra[index],str_arra[index]);
    15                 valueMap.put(str_arra[index],true);
    16             }else if (!map.get(p_arra[index]).equals(str_arra[index])) return false;
    17             index++;
    18         }
    19         return true;        
    20     }
  • 相关阅读:
    HTML笔记
    Android自定义View 自定义组合控件
    CSS 笔记
    HTML 4.01 快速参考
    MSP430单片机之中断服务
    MSP430单片机之RTC实时时钟
    Centos7.4内核符号地址查找函数的BUG
    珍惜世上的五个人
    实习
    毕业后的五年拉开大家差距的原因在哪里
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7718898.html
Copyright © 2011-2022 走看看