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;
        }
    }
  • 相关阅读:
    SQLServer DMV Query
    SQL Server Logical/Physical Reads
    The include feature of SQL Server Index
    数据库教程:数据库常用对象
    数据库教程:数据库组成
    数据库教程(一):基本概念
    C#编程:依赖倒置原则DIP
    C#编程:AOP编程思想
    ASP.NET Core Web服务器
    DataTable实现分组
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5836153.html
Copyright © 2011-2022 走看看