class Solution { public boolean wordPattern(String pattern, String s) { //split the string to string[] String[] words = s.split(" "); //splitting at space //check if lengths are same if(words.length != pattern.length()) return false; //make a frequency map and map letters to strings HashMap<Character , String > map = new HashMap<>(); for(int i =0 ;i < pattern.length();i++){ char ch = pattern.charAt(i); //check if ch is already present in the hashmap if(map.containsKey(ch)){ //check if old and new mapped values are same if(map.get(ch).equals(words[i]) == false) return false; } //if ch is not present in the hashmap else{ //but word is already mapped if(map.containsValue(words[i])) return false; map.put(ch , words[i]); } } return true; } }