zoukankan      html  css  js  c++  java
  • 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:
    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.
    Notes:
    You may assume pattern contains only lowercase letters, and str contains lowercase letters separated by a single space.

    注意这是一一映射,也就是说如果a->dog, b->dog,就应该return false,所以应该在HashMap基础上再加一层检查,即若不含该key,加入map之前应该检查map.values().contains(String)

    第二遍:use HashMap和HashSet

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            if (pattern==null || str==null) return false;
            String[] all = str.split(" ");
            
            if (pattern.length() != all.length) return false;
            HashMap<Character, String> map = new HashMap<Character, String>();
            HashSet<String> set = new HashSet<String>();
            for (int i=0; i<pattern.length(); i++) {
                char cur = pattern.charAt(i);
                if (!map.containsKey(cur)) {
                    if (set.contains(all[i])) return false;
                    map.put(pattern.charAt(i), all[i]);
                    set.add(all[i]);
                }
                else {
                    if (!map.get(cur).equals(all[i]))
                        return false;
                }
            }
            return true;
        }
    }
    

      用 map.values().contains()

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            if (pattern==null || str==null) return false;
            String[] all = str.split(" ");
            
            if (pattern.length() != all.length) return false;
            HashMap<Character, String> map = new HashMap<Character, String>();
            for (int i=0; i<pattern.length(); i++) {
                if (!map.containsKey(pattern.charAt(i))) {
                    if (map.values().contains(all[i])) return false;
                    map.put(pattern.charAt(i), all[i]);
                }
                else {
                    if (!map.get(pattern.charAt(i)).equals(all[i]))
                        return false;
                }
            }
            return true;
        }
    }
    

      

  • 相关阅读:
    js_未结束的字符串常量
    [转]关于项目管理的思考
    Nhibernate理解
    Visual Studio 2005常用插件搜罗
    基本概念
    resharper 2.0
    Nhibernate资源
    [转]关于项目管理的知识点
    style
    带分数 蓝桥杯
  • 原文地址:https://www.cnblogs.com/apanda009/p/7791319.html
Copyright © 2011-2022 走看看