• Word Pattern


    Given a pattern and a string str, find if str follows the same pattern.

    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:

    1. patterncontains only lowercase alphabetical letters, and str contains words separated by a single space. Each word in str contains only lowercase alphabetical letters.
    2. Both pattern and str do not have leading or trailing spaces.
    3. Each letter in pattern must map to a word with length that is at least 1.

    用两个Hashmap!

      

     1     public boolean wordPattern(String pattern, String str) 
     2     {
     3         String[] words;
     4         Map<String, Character> map1 = new HashMap<>();
     5         Map<Character,String> map2 = new HashMap<>();
     6         words = str.split(" ");
     7         if(pattern.length()!=words.length) return false;
     8         for(int i = 0; i<words.length;i++)
     9         {
    10             if(map1.containsKey(words[i]))
    11             {
    12                 Character index = map1.get(words[i]);
    13                 if (index != pattern.charAt(i)) return false;
    14             }
    15             
    16             
    17             if(map2.containsKey(pattern.charAt(i)))
    18             {
    19                 String index = map2.get(pattern.charAt(i));
    20                 if (!index.equals(words[i])) return false;
    21             }
    22             
    23             
    24             map1.put(words[i],pattern.charAt(i));
    25             map2.put(pattern.charAt(i),words[i]);
    26         }
    27         return true;
    28     
    29     }
  • 相关阅读:
    浏览器滚动条高度的获取与设置
    aspx页面 按钮不响应回车键
    HTML5 canvas 圆盘抽奖
    spark 解决大文件造成的分区数据量过大的问题
    简单http文件服务器 (Python)
    调试分析工具 (C/C++)
    案例学习——网站高并发处理相关技术
    一致性哈希
    Linux 环境下程序不间断运行
    案例分析——BAT业务https化经历
  • 原文地址:https://www.cnblogs.com/hygeia/p/4858307.html
Copyright © 2020-2023  润新知