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;
            
        }
    }
  • 相关阅读:
    微信开发 缓存处理
    ASP.NET MVC 开发日常笔记
    微信开发笔记
    Kindeditor 编辑代码过滤
    PS 使用技巧
    Javascript 日常开发用到的小知识点
    C# 下载文件
    Javascript 笔记一
    C# 知识巩固三
    文献笔记(五)
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/5178433.html
Copyright © 2011-2022 走看看