zoukankan      html  css  js  c++  java
  • 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.

    Credits:
    Special thanks to @minglotus6 for adding this problem and creating all test cases.

    Solution:

    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            if (str.isEmpty() && pattern.isEmpty()) return true;
            if (str.isEmpty() || pattern.isEmpty()) return false;
            
            String[] map = new String[26];
            Arrays.fill(map,"");
            String[] words = str.split(" ");
            HashSet<String> assigned = new HashSet<String>();
            
            if (pattern.length()!=words.length) return false;
            
            for (int i=0;i<pattern.length();i++){
                char code = pattern.charAt(i);
                if (!map[code-'a'].isEmpty()){
                    // code.word != word, it is wrong
                    if (!map[code-'a'].equals(words[i])){
                        return false;
                    }
                } else {
                    // code.word is empty but word has been assigned to another code, it is wrong.
                    if (assigned.contains(words[i])){
                        return false;
                    }
                    assigned.add(words[i]);
                    map[code-'a'] = words[i];
                }
            }
            return true;
        }
    }
  • 相关阅读:
    Realtime crowdsourcing
    maven 常用插件汇总
    fctix
    sencha extjs4 command tools sdk
    首次吃了一颗带奶糖味的消炎药,不知道管用不
    spring mvc3 example
    ubuntu ati driver DO NOT INSTALL recommand driver
    yet another js editor on windows support extjs
    how to use springsource tools suite maven3 on command
    ocr service
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5836153.html
Copyright © 2011-2022 走看看