You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🔥 Word Pattern 🔥 || Simple Fast and Easy || with Explanation
Solution - 1
import'dart:collection';
classSolution {
boolwordPattern(String pattern, String s) {
// s is the sentence so we breaking it into each and every single wordList<String> words = s.split('');
// Two HashMapif (words.length != pattern.length) returnfalse;
HashMap<int, String> firstHashMap =HashMap();
HashMap<String, bool> secondHashMap =HashMap();
// looping through each and every characterfor (int i =0; i < pattern.length; i++) {
// getting the char code of every patternint char = pattern.codeUnitAt(i);
// because it has sentence so we taking the each character and making into a a single word// to compare with the charif (firstHashMap.containsKey(char) ==false) {
if (secondHashMap.containsKey(words[i]) ==true) {
returnfalse;
} else {
secondHashMap[words[i]] =true;
firstHashMap[char] = words[i];
}
} else {
String mWith = firstHashMap[char]!;
if (mWith.allMatches(words[i]) ==false) {
returnfalse;
}
}
}
returntrue;
}
}
Solution - 2
import'dart:collection';
classSolution {
boolwordPattern(String pattern, String s) {
// initializing HashMap because it's fastfinalHashMap<String, String> map =HashMap();
// splitting the sentence into each individual characterfinalList<String> words = s.split(' ');
finalList<String> patternWords = pattern.split('');
// if the length is not sameif (words.length != patternWords.length) returnfalse;
// looping through each and every individual pattern wordfor (int i =0; i < patternWords.length; i++) {
// if the key is null or emptyif (map[patternWords[i]] ==null) {
// but value contain itif (map.containsValue(words[i])) {
returnfalse;
}
// assign each and every character and word
map[patternWords[i]] = words[i];
} else {
// if they are nt assign than falseif (map[patternWords[i]] != words[i]) {
returnfalse;
}
}
}
returntrue;
}
}