码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode_290. Word Pattern

时间:2019-11-01 16:03:27      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:and   length   code   pre   string   you   div   ash   arrays   

 

290. Word Pattern

Easy

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.

Example 1:

Input: pattern = "abba", str = "dog cat cat dog"
Output: true

Example 2:

Input:pattern = "abba", str = "dog cat cat fish"
Output: false

Example 3:

Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false

Example 4:

Input: pattern = "abba", str = "dog dog dog dog"
Output: false

Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.

 

package leetcode.easy;

public class WordPattern {
	@org.junit.Test
	public void test() {
		String pattern1 = "abba";
		String str1 = "dog cat cat dog";
		String pattern2 = "abba";
		String str2 = "dog cat cat fish";
		String pattern3 = "aaaa";
		String str3 = "dog cat cat dog";
		String pattern4 = "abba";
		String str4 = "dog dog dog dog";
		System.out.println(wordPattern(pattern1, str1));
		System.out.println(wordPattern(pattern2, str2));
		System.out.println(wordPattern(pattern3, str3));
		System.out.println(wordPattern(pattern4, str4));
	}

	public boolean wordPattern(String pattern, String str) {
		String[] arrays = str.split(" ");
		if (arrays.length != pattern.length()) {
			return false;
		}

		java.util.Map<String, Character> map = new java.util.HashMap<>();
		for (int i = 0; i < pattern.length(); i++) {
			if (map.containsKey(arrays[i]) && map.get(arrays[i]) != pattern.charAt(i)) {
				return false;
			} else if (!map.containsKey(arrays[i]) && map.containsValue(pattern.charAt(i))) {
				return false;
			} else {
				map.put(arrays[i], pattern.charAt(i));
			}
		}
		return true;
	}
}

 

LeetCode_290. Word Pattern

标签:and   length   code   pre   string   you   div   ash   arrays   

原文地址:https://www.cnblogs.com/denggelin/p/11777309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!