### 题目描述：

You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes.

Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.

Given a non-empty string S and a number K, format the string according to the rules described above.

Example 1:

```Input: S = "5F3Z-2e-9-w", K = 4

Output: "5F3Z-2E9W"

Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.```

Example 2:

```Input: S = "2-5g-3-J", K = 2

Output: "2-5G-3J"

Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above.```

Note:

1. The length of string S will not exceed 12,000, and K is a positive integer.
2. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
3. String S is non-empty.

### 说明：

1、给定一个字符串S和一个正数K，字符串中只含有字母、数字和破折号，比如5F3Z-2e-9-w。

2、题意清晰，这道题我们要从字符串的最后开始处理，这样比较方便。

```    string licenseKeyFormatting(string S, int K)
{
string res;//最后要返回的字符串
int i=S.size()-1,count=0;
while(i>=0)
{
if(S[i]!='-')//如果这个字符是字母或者数字
{
count++;
if(count<=K)//如果还没有达到K个
{
res+=char(toupper(S[i]));//大小写转换，增加到res中
i--;
}
else//如果达到了K个
{
res+='-';//插入'-'
count=0;//重新开始计数
}
}
else//如果这个字符是'-'
i--;
}
reverse(res.begin(),res.end());//最后反转一下，就是我们要的字符串。
return res;
}```

3、一些其他说明：

205 篇文章43 人订阅

0 条评论

## 相关文章

10340

### 值类型和引用类型的区别，struct和class的区别

C#值类型和引用类型 1、简单比较 　　值类型的变量直接存储数据，而引用类型的变量持有的是数据的引用，数据存储在数据堆中。 　　值类型（value type）：...

25810

9120

2.4K100

11520

22770

11130

38650

10810

34390