zoukankan      html  css  js  c++  java
  • Java [Leetcode 290]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.

    解题思路:

    使用HashMap来做。

    代码如下:

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

      

  • 相关阅读:
    TCP四次握手断开连接(十一)
    Go-函数
    Go-数据类型以及变量,常量
    GO语言介绍以及开发环境配置
    Socket与WebSocket以及http与https重新总结
    希尔排序
    第19课
    第18课
    外传篇3 动态内存申请的结果
    外传篇2 函数的异常规格说明
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5184082.html
Copyright © 2011-2022 走看看