题目
Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.
We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.
So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.
翻译
假设给定一个字符串,这个字符串代表软件的许可码。字符串由数字,字母以及分隔符组成。破折号分割字符串中的字母数字字符组。
我们希望每组的字符个数长度为K。除过第一组,可以比K短,但是必须只要有一个字符。为了满足要求,我们需要重新插入分割符。另外,所有小写字母必须转换成大些字母。
给定的字符串S没空,代表许可码。整数K表示,需要更具上述描述规则重新返回符合格式的许可吗。
思路
1,首先将所有的非分割符字符组成新的字符串S1
2,对S1进行处理,首先计算S1长度。如果S1 % K 不等于0,则需要对第一组进行特殊处理
3,然后对其他字符串,每隔K个插入’-‘即可。
代码
class Solution {
public:
string getTheChar(string &s){
string res = "";
for(int i = 0; i < s.size(); i++){
if(s[i] != '-'){
res += s[i];
}
}
return res;
}
string licenseKeyFormatting(string S, int K) {
string res = "";
string t = getTheChar(S);
int charNum = t.size();
int firstN = charNum%K;
int time = charNum/K;
int i = 0;
if(firstN){
for(int j = 0; j < firstN;j++){
if(isalpha(t[i]) && islower(t[i])){
res+= toupper(t[i]);
}else{
res += t[i];
}
i++;
}
res += "-";
}
for(int j = 0; j < time; j++ ){
for(int l = 0; l < K; l++){
if(isalpha(t[i]) && islower(t[i])){
res+= toupper(t[i]);
}else{
res += t[i];
}
i++;
}
res += "-";
}
res.pop_back();
return res;
}
};