290. Word Patterncss
Given a pattern
and a string str
, find if str
follows the same pattern.java
Here follow means a full match, such that there is a bijection between a letter in pattern
and a non-empty word in str
.spa
Example 1:code
Input: pattern = , str = Output: true"abba""dog cat cat dog"
Example 2:blog
Input:pattern = , str = Output: false"abba""dog cat cat fish"
Example 3:leetcode
Input: pattern = , str = Output: false"aaaa""dog cat cat dog"
Example 4:get
Input: pattern = , str = Output: false"abba""dog dog dog dog"
Notes:
You may assume pattern
contains only lowercase letters, and str
contains lowercase letters that may be separated by a single space.string
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; } }