leetcode:1309. 解碼字母到整數映射(c++)

這種映射題目的一種想法是找到它和初值的差距,然後與初值加和即可。

class Solution {
public:
    string freqAlphabets(string s) {
        int map = 96;    // a前面一個數的ascii碼
        string res;	     // 結果字符串
        for(int i = 0; i < s.size(); i ++)	//遍歷s字符串
        {
        	//分兩種情況,沒遇到‘#’就把單字符添加到res字符串中
            if(s[i] != '#')
            {
                int temp = (int)s[i] - '0';
                res +=  char(temp+map);
            }
            //遇到'#'就刪掉前兩個字符,然後把s前兩個字符提出來
            //並轉成與初始值的差值
            else
           {
                res.erase(res.size()-2,2);    //刪掉res前兩個字符
                string substr = s.substr(i-2,2);	//取s字符串前兩個字符,此字符串爲差值
                char tem = map + atoi(substr.c_str()); //與初始值加和
                res += tem;
           }
        }
        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章