数据结构基础day6

题目:415. 字符串相加

我的做法:一位一位处理

从字符串的最后一位开始处理,知道短字符串处理结束,然后开始处理进位问题,注意考虑’999’和’1’想加的特殊情况

class Solution {
    
    
public:
    string addStrings(string num1, string num2) {
    
    
        int s=num1.size()-1, t=num2.size()-1;   //默认s<t
        if(s>t) return addStrings(num2, num1);	//如果长字符串在前,需要调换位置
        bool p = false;	//进位判断
        while(s>=0){
    
    	//以短字符串处理结束为判断依据
            int temp = (num2[t]-'0')+(num1[s]-'0');	//每位相加结果
            if(p){
    
    	//如果前一位有进位,注意加上
                ++temp;
                p = false;
            }
            if(temp>=10){
    
    	//如果相加结果大于等于10,进位
                p = true;
                temp = temp-10;
            }
            num2[t] = temp + '0';	//修改该位字符
            --s; --t;	//向前遍历
        }
        while(p && t>=0){
    
    	//短字符遍历结束后,处理长字符串的进位,一直处理到长字符串开头
            int temp = num2[t]-'0'+1;	//有进位,t项字符+1
            if(temp>=10){
    
    	//t位需要向前进位
                p=true;	//p继续为true
                num2[t] = temp-10+'0';	//修改t位
                --t;	//向前遍历
            }else{
    
    	//t位不需要向前进位
                num2[t]=temp+'0';
                p = false;	//p为false,退出循环
            }
        }
        if(p){
    
    	//如果长字符串还要进位,例如999+1=1000
            num2 = '1'+num2;	//前面加个1
        }
        return num2;
    }
};

其他解法:模拟

当短字符串指针大于字符长度,所指内容为0,相当于前面补0

class Solution {
    
    
public:
    string addStrings(string num1, string num2) {
    
    
        string ans = "";	//初始化一个空字符串
        int s = num1.size()-1, t = num2.size()-1, temp=0;	//两个字符串的长度s,t,以及进位temp
        int add1, add2;	//字符串第t位的值
        while(s>=0 || t>=0 || temp!=0){
    
    	//按照更长的字符串长度进行计算,或者还有进位没有处理完
            if(s>=0) add1 = num1[s]-'0';	//当字符串t位有具体值,add1为字符值
            else add1 = 0;	//当字符串t位没有具体值,add1=0
            if(t>=0) add2 = num2[t]-'0';	//同上
            else add2 = 0;
            temp = add1 + add2 + temp;	//新值=add1+add2+进位
            ans.push_back(temp%10+'0');	//存储新值,注意用push_back
            temp = temp/10;	//更新进位值
            --s; --t;	//向前遍历
        }
        reverse(ans.begin(), ans.end());	//翻转ans字符串
        return ans;
    }
};

题目:409. 最长回文串

我的做法:

统计每个字符的频次,双数都加,单数可以-1加(而不是选最长的)

class Solution {
    
    
public:
    int longestPalindrome(string s) {
    
    
        int ans=0;
        bool dan = false;	//判断是否有频次为单数的字符
        unordered_map<char, int> map;	//hash存储字符出现频次
        for(char c:s){
    
    
            ++map[c];
        }
        for(auto m:map){
    
    	//遍历每个map
            ans+=m.second/2*2;	//双数就直接加n,单数就加n-1
            if(m.second%2==1){
    
    	//有单数字符,dan=true
                dan = true;
            }
        }
        if(dan) ans++;	//有单数字符,ans++
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43606119/article/details/130305003