problem
solution1:
倒着处理,注意第一个字符为分隔符的情况要进行删除,注意字符的顺序是否正序。
class Solution {
public:
string licenseKeyFormatting(string S, int K) {
if(S.size()<=) return NULL;
int cnt = ;
string ans = "";
for(int i=S.size()-; i>=; i--)//倒着处理.
{
char c = S[i];
if(S[i]=='-') continue;
else if(S[i]>='a'&&S[i]<='z') c = S[i] - ;
ans.push_back(c);
cnt++;
if(cnt%K==)//
{
ans.push_back('-');
}
}
//if(!ans.empty() && ans.back()=='-') ans.pop_back();
int s = ans.size();
string ans1;
if(ans.back()=='-') ans1 = ans.substr(, s-);
else ans1 = ans;
return string(ans1.rbegin(), ans1.rend());// }
};
参考
1. Leetcode_482. License Key Formatting;
2. GrandYang;
完