Q27 Word Pattern - LeetCode
Thu Jan 26 2023 12:45:38 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
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;
}
}
content_copyCOPY
https://leetcode.com/problems/word-pattern/
Comments