zoukankan      html  css  js  c++  java
  • Leetcode 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. Both pattern and str contains only lowercase alphabetical letters.
    2. Both pattern and str do not have leading or trailing spaces.
    3. Each word in str is separated by a single space.
    4. Each letter in pattern must map to a word with length that is at least 1.

     解题思路:

    使用HashMap, pattern 里的character 对应str 里的word.

    注意:pattern = "abba", str = "dog dog dog dog" should return false.

    即当map里不包含key 时,还要检查是否已包含Value, 如果已含,那么return false.

    另外,分割space 使用str.split("\s+")


    Java code:

    public boolean wordPattern(String pattern, String str) {
             String[] splited = str.split("\s+");
             if(pattern.length() != splited.length) {
                 return false;
             }
             Map<Character, String> map = new HashMap<Character, String>();
             for(int i = 0; i < pattern.length(); i++){
                 if(!map.containsKey(pattern.charAt(i))) {
                     if(map.containsValue(splited[i])){
                         return false;
                     }
                     map.put(pattern.charAt(i), splited[i]);
                 }else{
                     if(!map.get(pattern.charAt(i)).equals(splited[i])){
                         return false;
                     }
                 }
             }
             return true;
        }
  • 相关阅读:
    redis网络资料汇总
    Spring攻略学习笔记(3.01)在Spring中启用AspectJ注解支持
    [C/C++]福尔摩斯 ABCDE*?=EDCBA
    MyBatis测试范例
    使用TileMap制作游戏地图,在cocos2dx中使用(一)
    Tomcat7 catalina.out 日志分割
    MyBatis之User.xml
    基于 SIP webRTC 架构的系统部署模型分析
    第42周星期二
    第41周星期三小结
  • 原文地址:https://www.cnblogs.com/anne-vista/p/4856667.html
Copyright © 2011-2022 走看看