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:
- pattern =
"abba"
, str ="dog cat cat dog"
should return true. - pattern =
"abba"
, str ="dog cat cat fish"
should return false. - pattern =
"aaaa"
, str ="dog cat cat dog"
should return false. - pattern =
"abba"
, str ="dog dog dog dog"
should return false.
<pre name="code" class="java"> public boolean wordPattern(String pattern, String str) { boolean flag = false; int length1 = pattern.length(); String[] str1 = str.split(" "); int length2 = str1.length; int count = 0; HashMap map1 = new HashMap(); HashMap map2 = new HashMap(); int[] array1= new int[length1]; int[] array2= new int[length2]; if(length1 != length2) flag = false; else{ for(int i = 0; i < length1; i++){ if(map1.containsKey(String.valueOf(pattern.charAt(i)))){ array1[i] = map1.get(String.valueOf(pattern.charAt(i))); } else{ map1.put(String.valueOf(pattern.charAt(i)), i); array1[i] = i; } if(map2.containsKey(str1[i])){ array2[i] = map2.get(str1[i]); } else{ map2.put(str1[i], i); array2[i] = i; } } for(int i = 0; i < length1; i++){ if(array1[i] == array2[i]){ count ++; } } if(count == length1){ flag = true; } } return flag; }