zoukankan      html  css  js  c++  java
  • LeetCode:Word Pattern

    problem:

    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.

    Subscribe to see which companies asked this question

    Solution:
    public class Solution {
        public boolean wordPattern(String pattern, String str) {
            if (pattern.isEmpty() || str.isEmpty()) {
                return false;
            }
             
            String[] s = str.split(" ");
            if (s.length != pattern.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(s[i])) {
                        return false;
                    }
                } else if (hashMap.containsValue(s[i])) {
                    return false;
                } else {
                    hashMap.put(pattern.charAt(i), s[i]);
                }
            }
             
            return true;
            
        }
    }
  • 相关阅读:
    WPF中ListBoxItem绑定一个UserControl的学习
    Server.Transfer和Response.Redirect的区别
    4个程序员的一天
    (转)让ADO.NET Entity Framework支持Oracle数据库
    IIS操作类
    HttpHandler与HttpModule区别
    网站性能优化的34条黄金法则
    oracle9i/10g/11g各种下载
    WCF简要介绍
    软件系统的稳定性
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/5178433.html
Copyright © 2011-2022 走看看