482 License Key Formatting 注册码格式化

详见:https://leetcode.com/problems/license-key-formatting/description/

C++:

class Solution {
public:
    string licenseKeyFormatting(string S, int K)
    {
        string res = "";
        int cnt = 0, n = S.size();
        for (int i = n - 1; i >= 0; --i) 
        {
            char c = S[i];
            if (c == '-')
            {
                continue;
            }
            if (c >= 'a' && c <= 'z')
            {
                c -= 32;
            }
            res.push_back(c);
            if (++cnt % K == 0) 
            {
                res.push_back('-');
            }
        }
        if (!res.empty() && res.back() == '-')
        {
            res.pop_back();
        }
        return string(res.rbegin(), res.rend());
    }
};

 参考:https://www.cnblogs.com/grandyang/p/6277972.html

posted on 2018-04-21 21:18  lina2014  阅读(145)  评论(0编辑  收藏  举报

导航