数据结构基础day8

题目:字母异位词分组

我的做法:排序字符串,哈希表判断

class Solution {
    
    
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
    
    
        int n = strs.size();
        if(n==0) return{
    
    };	//特判
        unordered_map<string, vector<int>> map;	//建立字母异位词对应下标的哈希表
        vector<vector<string>> ans;	//返回结果
        for(int i=0; i<n; ++i){
    
    	//遍历字符串数组
            string temp = strs[i];	//取出每个字符串
            sort(temp.begin(), temp.end());	//排序
            if(map.count(temp)){
    
    	//如果map中已经存在该字母异位词,存储下标
                map[temp].push_back(i);
            }else{
    
    	//map中没有这个类型的字母异位词
                map[temp] = {
    
    i};	//存储该字母异位词和下标
            }
        }
        for(auto m:map){
    
    	//遍历hash表
            vector<string> temp;	//存储相同字母异位词的字符串数组
            for(int i=0; i<m.second.size(); ++i){
    
    	//遍历字母异位词对应下标数组
                temp.push_back(strs[m.second[i]]);	//将对应字符串存入temp中
            }
            ans.push_back(temp);	//temp入ans
        }
        return ans;
    }
};

其他解法:优化

class Solution {
    
    
public:
    vector<vector<string>> groupAnagrams(vector<string>& strs) {
    
    
        unordered_map<string, vector<string>> map;	//哈希表的value设置成字符串数组,存储字母异位词
        vector<vector<string>> ans;
        for(string str:strs){
    
    
            string temp = str;
            sort(temp.begin(), temp.end());
            map[temp].emplace_back(str);	//emplace_back是push_back的优替,节省内存和耗时
        }
        for(auto it = map.begin(); it!=map.end(); ++it){
    
    
            ans.emplace_back(it->second);	//迭代器才能->second取值
        }
        return ans;
    }
};

题目:43. 字符串相乘

解法:做乘法

两数相乘,结果要么为m+n,要么为m+n-1,于是声明一个m+n的数组存储结果,第i位和第j位相乘的结果放在i+j+1上,然后处理进位

class Solution {
    
    
public:
    string multiply(string num1, string num2) {
    
    
        int m = num1.size(), n = num2.size();
        if(num1=="0" || num2=="0") return "0";	//特判,其中一个为0,结果为0
        vector<int> num(m+n);	//存储相乘结果
        for(int i=m-1; i>=0; --i){
    
    	//取num1的i位数
            int x = num1[i]-'0';
            for(int j=n-1; j>=0; --j){
    
    	//取num2的j位数
                int y = num2[j]-'0';
                num[i+j+1] += x * y;	//结果累加到i+j+1位,注意是累加不是赋值
            }
        }
        for(int i=m+n-1; i>0; --i){
    
    	//处理进位,注意i的范围
            num[i-1] += num[i]/10;
            num[i] = num[i]%10;
        }
        int index = num[0]==0 ? 1:0;	//处理最高位,如果m+n位为0,去掉
        string ans;	//返回的答案
        while(index<m+n){
    
    	//将相乘结果存入ans
            ans.push_back(num[index]);	//注意是push_back,不是ans[index] = num[index]
            ++index;
        }
        for(auto &ch:ans){
    
    	//int转换为char
            ch = ch + '0';
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43606119/article/details/130342423
今日推荐