• LeetCode--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、对应的pattern - str是可以用hashmap组成的键值对;

                   2、主要判断的是:map中是否存在key :    

                                                     1、若不存在key,但存在value,则返回false;  

                                                     2、若存在key,  但是value与str的对应字符串不等,返回false;

                                          若都不存在,就添加新的 k-v对;

    public class Solution {
         
        /**
         * 字符串模式匹配
         * @param pattern
         * @param str
         * @return
         */
       public boolean wordPattern(String pattern, String str) {
            if (pattern.isEmpty() || str.isEmpty())
                return false;
            String[] string = str.split(" ");
            if (pattern.length() != string.length)
                return false;

            HashMap<Character, String> hashMap = new HashMap<Character, String>();
            for (int i = 0; i < pattern.length(); i++) {
                if (hashMap.containsKey(pattern.charAt(i))) {
                    if (!hashMap.get(pattern.charAt(i)).equals(string[i]))
                        return false;
                } else if (hashMap.containsValue(string[i]))
                    return false;
                else
                    hashMap.put(pattern.charAt(i), string[i]);
            }
                    return true;
        }
    }

    总结: 1、splith函数:在java.lang包中有String.split()方法,返回是一个数组    (http://www.cnblogs.com/liubiqu/archive/2008/08/14/1267867.html)   

             2、HashMap的各种操作:详见 http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4

             3、字符串操作:              详见  http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    Queueing at Bank【PAT 1017题】
    table标签的布局
    股票投资的24堂必修课1
    股票投资的24堂必修课2基本面分析
    Eclipse最全快捷键 分享便捷与快乐
    浅析将matlab函数编译成dll供Cpp调用的方法
    Python编程语言中调用Matlab绘制保存数据的方案
    Eclipse中10个最有用的快捷键组合
    WPF 4 DataGrid 控件(进阶篇二)
    VBS 操作 IIS
  • 原文地址:https://www.cnblogs.com/neversayno/p/5119006.html
Copyright © 2020-2023  润新知