• 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

    态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
  • 相关阅读:
    Java的字符串及格式化输入输出
    Java的数据类型与类型转换
    java基本程序
    svn基础入门
    github基础入门笔记
    git基础入门笔记
    linux基础入门笔记
    二、FreeMarker 模版开发指南 第二章 数值和类型
    【CodeForces】[599B]Spongebob and Joke
    【CodeForces】[612B]HDD is Outdated Technology
  • 原文地址:https://www.cnblogs.com/neversayno/p/5119006.html
Copyright © 2020-2023  润新知