iT邦幫忙

2024 iThome 鐵人賽

DAY 3
0

題目

1945. Sum of Digits of String After Convert
難度: 簡單

題意

給定一字串s與整數k
將字串s中的字元按照字母序轉換成整數(a->1, 'b'->2...),將整數排在一起形成新的整數("abax"->262124)
接著做k次操作;每次操作將每個digits相加,形成一個新的整數(262124->17)

方向

這種題目類型我稱之為模擬,只要按照題目的說明把程式打出來就好,沒什麼營養。
唯一要注意的,是字元不是轉換成ascii編碼,而是按照1-index順序轉換。

實作

class Solution
{
public:
    int getLucky(string s, int k)
    {
        vector<int> convert;
        for (auto c : s)
        {
            int curr = c - 'a' + 1;
            if (curr / 10)
                convert.push_back(curr / 10);
            convert.push_back(curr % 10);
        }

        for (int i = 0; i < k; i++)
        {
            int sum = accumulate(convert.begin(), convert.end(), 0);
            convert.clear();
            while (sum)
            {
                convert.push_back(sum % 10);
                sum /= 10;
            }
            reverse(convert.begin(), convert.end());
        }

        int res = 0;
        for (int i = 0; i < (int) convert.size(); i++)
        {
            res *= 10;
            res += convert[i];
        }
        return res;
    }
};

分析

時間複雜度: O(N),遍歷整個字串長度N以轉換成整數;轉換後陣列長度最多2N,因此接下來的k次操作也都是O(N)
空間複雜度: O(N),建了字串長度的整數陣列

結果

Time Submitted Status Runtime Memory Language
09/03/2024 18:34 Accepted 0 ms 8.2 MB cpp

上一篇
[9/2] 找換粉筆的傢伙
下一篇
[9/4] 所以我停下來 然後雙手打開
系列文
菜就多練,不會就多刷26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言