【leetcode】482. License Key Formatting

problem

482. License Key Formatting

solution1:

倒着处理,注意第一个字符为分隔符的情况要进行删除,注意字符的顺序是否正序。

class Solution {
public:
    string licenseKeyFormatting(string S, int K) {
        if(S.size()<=0) return NULL;
        int cnt = 0;
        string ans = "";
        for(int i=S.size()-1; i>=0; i--)//倒着处理.
        {
            char c = S[i];
            if(S[i]=='-') continue;
            else if(S[i]>='a'&&S[i]<='z') c = S[i] - 32;
            ans.push_back(c);
            cnt++;
            if(cnt%K==0)// 
            {
                ans.push_back('-');
            }
        }
        //if(!ans.empty() && ans.back()=='-') ans.pop_back();
        int s = ans.size();
        string ans1;
        if(ans.back()=='-') ans1 = ans.substr(0, s-1);
        else ans1 = ans;
        return string(ans1.rbegin(), ans1.rend());//
        
    }
};

参考

1. Leetcode_482. License Key Formatting;

2. GrandYang;

原文地址:https://www.cnblogs.com/happyamyhope/p/10592187.html