本题源自leetcode 482
—————————————————–
思路:从后向前遍历字符串。如果结果字符串的长度 余 K+1 等于 K,则下一个字符是 – 。
2 反转结果字符串
代码:
string licenseKeyFormatting(string S, int K) {
string res;
for(auto i = S.rbegin(); i < S.rend(); i++){
if(*i != '-'){
if(res.size() % (K + 1) == K)
res += '-';
res += toupper(*i);
}
}
reverse(res.begin(),res.end());
return res;
}