Given a pattern
and a string s
, find if s
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 s
.
https://leetcode.com/problems/word-pattern/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Solution { public boolean wordPattern(String pattern, String s) { String[] sArr = s.split(" "); Map<Character, String> map = new HashMap<>(); char[] pArr = pattern.toCharArray(); //if the length of the pattern doesn't match the splitted string //return false if(pArr.length != sArr.length){ return false; } for(int i=0;i<pArr.length;i++){ //if the map doesn't contain a character pArr[i] from the pattern //then check if it contains the string sArr[i] if(!map.containsKey(pArr[i])){ if(!map.containsValue(sArr[i])){ map.put(pArr[i], sArr[i]); } else //if the map contains the string sArr[i] return false //since it has already been associated with the some other character pArr[i] return false; } //if the string associated with a character pArr[i] matches the string sArr[i] if(!map.get(pArr[i]).equals(sArr[i])){ return false; } } return true; } } |