1 <= pattern.length <= 300 pattern contains only lower-case English letters. 1 <= s.length <= 3000 s contains only lowercase English letters and spaces ' '. s does not contain any leading or trailing spaces. All the words in s are separated by a single space.
classSolution { public: boolwordPattern(string pattern, string s){ // create two maps to store the mapping between characters and words unordered_map <char, string> charMatch; unordered_map <string, char> stringMatch; // create a pointer to point to the pattern int patternPointer = 0; string word = ""; // create a counter to count the number of words int wordCounter = 0; for (int i = 0; i <= s.size(); i++){ // if we reach the end of the string or we reach a space if (s[i] == ' ' || i == s.size()){ auto find = charMatch.find(pattern[patternPointer]); auto findS = stringMatch.find(word); // if we don't find the element in the map if (find == charMatch.end() && findS == stringMatch.end()){ // insert the element into the map charMatch[pattern[patternPointer]] = word; stringMatch[word] = pattern[patternPointer]; word = ""; patternPointer ++; wordCounter ++; } else{ // if we find the element in the map but the mapping is not correct if (charMatch[pattern[patternPointer]] != word || stringMatch[word] != pattern[patternPointer]) returnfalse; else{ word = ""; patternPointer ++; wordCounter ++; } } } else word += s[i]; } // if the number of words is not equal to the number of characters if (wordCounter != pattern.size()) returnfalse; returntrue; } };
Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Example 1:
Input: s = "anagram", t = "nagaram" Output: true Example 2:
Input: s = "rat", t = "car" Output: false
Constraints:
1 <= s.length, t.length <= 5 * 104 s and t consist of lowercase English letters.
classSolution { public: boolisAnagram(string s, string t){ unordered_map <char, int> wordCount; // count the number of characters in s for (int i = 0; i < s.size(); i++){ wordCount[s[i]] ++; } // check if the characters in t are in s for (int j = 0; j < t.size(); j++){ // if the character is not in s or the number of the character in t is more than in s if(wordCount[t[j]] == 0) returnfalse; // if the character is in s else wordCount[t[j]]--; } // check if there are any characters left in s for (int i = 0; i < s.size(); i++){ // if there are characters left in s if (wordCount[s[i]] != 0) returnfalse; } // if there are no characters left in s returntrue; } };