πΉ 14. Longest Common Prefix
π https://leetcode.com/problems/longest-common-prefix/
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
string prefix = "";
for(int i = 0; i < strs[0].size(); i++) {
string first = strs[0];
for (auto s: strs) {
if (i >= s.size() || first[i] != s[i]) {
return prefix;
}
}
prefix += first[i];
}
return prefix;
}
};πΉ 49. Group Anagrams
π https://leetcode.com/problems/group-anagrams/
π Approach 1: Sorting
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> um;
for(auto &i : strs){
string sorted_str = i;
sort(sorted_str.begin(), sorted_str.end());
um[sorted_str].push_back(i);
}
vector<vector<string>> ans;
for(auto &i: um){
ans.push_back(i.second);
}
return ans;
}
};π Approach 2: Frequency Count (Optimal)
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
map<vector<int>, vector<string>> um;
for(auto &i: strs) {
vector<int> freq(26);
for(auto &c: i)
freq[c - 'a']++;
um[freq].push_back(i);
}
vector<vector<string>> ans;
for(auto &i: um)
ans.push_back(i.second);
return ans;
}
};β οΈ Notes
unordered_mapfaster but canβt hash vector easilymapworks but slightly slower