• WordPattern


    题意:

    * 给定一个pattern和一个字符串str,找到如果str遵循相同的模式。
    * pattern = "abba",str = "dog cat cat dog"应该返回true。
    * pattern = "abba",str = "dog cat cat fish"应该返回false。

    leetcode给的答案:

    public static boolean wordPattern(String pattern, String str) {
    	    String[] words = str.split(" ");  //分割开str这个字符串
    	    if (words.length != pattern.length())  //如果长度不同,明显不符合题意,返回false
    	        return false;
    	    Map index = new HashMap();  //用map的解释见下边的分析
    	    for (Integer i=0; i<words.length; ++i)
    	        if (index.put(pattern.charAt(i), i) != index.put(words[i], i))
    	            return false;
    	    return true;
    	}
    	
    	//修改后
    	public static boolean wordPattern1(String pattern, String str) {
    	    String[] words = str.split(" ");
    	    if (words.length != pattern.length())
    	        return false;
    	    Map index = new HashMap();
    	    for (Integer i=0; i<words.length; ++i)
    	        if (!Objects.equals(index.put(pattern.charAt(i), i), index.put(words[i], i)))//修改后
    	            return false;
    	    return true;
    	}
    

    分析:

    Map的性质是:执行put函数时,如果key值存在,则覆盖key对应的value,并返回旧的value。本方法就用到了该性质,分析返回的值是否相等,判断两个字符串是不是按位对应关系,如下:

  • 相关阅读:
    交互式输入编辑与历史命令补全
    string模板
    textwrap——文本包裹和填充模块解析
    python质量控制
    命令自动补全模块rlcomplete
    密码输入模块getpass
    交互模式启动配置文件
    pprint模块解析
    python基础知识--2字符串
    python基础知识--1注释
  • 原文地址:https://www.cnblogs.com/K-artorias/p/7741699.html
Copyright © 2020-2023  润新知