zoukankan      html  css  js  c++  java
  • Word Pattern

    1、题目

    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:
    pattern = "abba", str = "dog cat cat dog" should return true.
    pattern = "abba", str = "dog cat cat fish" should return false.
    pattern = "aaaa", str = "dog cat cat dog" should return false.
    pattern = "abba", str = "dog dog dog dog" should return false.

    2、求解

     String[] words = str.split(" ");
            if (words.length != pattern.length())
                return false;
            Map index = new HashMap();
            for (Integer i=0; i<words.length; ++i) {
                //如果put的key不存在,则返回null
                //如果存在就返回之前的oldvalue
                Object put = index.put(pattern.charAt(i), i);
                Object put1 = index.put(words[i], i);
                if (put != put1)
                return false;
            }
            return true;

    重点解析:利用map.input(key,value)方法进行pattern到str的映射,同时利用map.input()方法的特点如何put的key不存在,就添加到map中,并且会返回null;否则更新value值,然后返回oldvalue的值。

    而这里的pattern和str的返回值应该是同步的






    欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
  • 相关阅读:
    Git 创建仓库并拉取代码
    Linux export 命令
    Linux ps 命令
    Linux sed 命令
    Linux find 命令
    Linux chmod 命令
    Linux chgrp 命令
    解除/配置 linux/nginx 的 tcp 连接(nginx配置文件日常配置推荐)
    更改Ubuntu的apt源
    anaconda 各版本的下载地址
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326890.html
Copyright © 2011-2022 走看看