From b844dd3b6e6fe1d099326328d57faf63b2ba3997 Mon Sep 17 00:00:00 2001 From: Ram Patil Date: Thu, 7 Nov 2024 21:24:38 -0800 Subject: [PATCH] Hashing1 Complete --- groupAna.cpp | 30 ++++++++++++++++++++++++++++++ isoStrings.cpp | 29 +++++++++++++++++++++++++++++ wordPattern.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) create mode 100644 groupAna.cpp create mode 100644 isoStrings.cpp create mode 100644 wordPattern.cpp diff --git a/groupAna.cpp b/groupAna.cpp new file mode 100644 index 00000000..b76d26cd --- /dev/null +++ b/groupAna.cpp @@ -0,0 +1,30 @@ +//we will assign prime no to each letters form a-z and then we will calculate the +//multiplication of each no if the multi is same then the string is an anargam and +//will move to that map else we will create new mapping for that index +//TC:0(nK) SC:O(n) +class Solution { +private: + double getHash(string&word){ + double hash = 1; + int primes[26] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101 +}; + for(auto&it:word){ + int key = it-'a'; + hash = hash*primes[key]; + } + return hash; + } +public: + vector> groupAnagrams(vector& strs) { + vector>ans; + unordered_map>mpp; + for(auto&qt:strs){ + double g = getHash(qt); + mpp[g].push_back(qt); + } + for(auto&ct:mpp){ + ans.push_back(ct.second); + } + return ans; + } +}; \ No newline at end of file diff --git a/isoStrings.cpp b/isoStrings.cpp new file mode 100644 index 00000000..3b0320a0 --- /dev/null +++ b/isoStrings.cpp @@ -0,0 +1,29 @@ +//use two maps to store mapping from both side +//Iterate tbrough string if maping is correct return true else false +//TC: O(n) SC O(n) +class Solution { +public: + bool isIsomorphic(string s, string t) { + unordered_mapsmap; + unordered_maptmap; + for(int i =0;ipts; + unordered_mapstp; + int j =0; + for(char c: pattern){ + if(j>=s.size())return false; + + string word = getWord(s,j); + //check if pattern is already in the map + auto it =pts.find(c); + //if it is already in the map and it is not mapped + // with the correctword return false + if(it!=pts.end() && it->second!=word){ + return false; + } + //checking the second map that if it is also mapped with the same ele + auto qt = stp.find(word); + if(qt!=stp.end() && qt->second!=c) return false; + // + pts[c] = word; + stp[word] = c; + } + if(j>=s.size())return true; + return false; + } +}; \ No newline at end of file