# 482.License Key Formatting

**482.License Key Formatting**

难度:Easy

> 给定一个密钥字符串S，只包含字母，数字以及 '-'（破折号）。N 个 '-' 将字符串分成了 N+1 组。给定一个数字 K，重新格式化字符串，除了第一个分组以外，每个分组要包含 K 个字符，第一个分组至少要包含 1 个字符。两个分组之间用 '-'（破折号）隔开，并且将所有的小写字母转换为大写字母。 给定非空字符串 S 和数字 K，按照上面描述的规则进行格式化。

```
示例 1：

输入：S = "5F3Z-2e-9-w", K = 4

输出："5F3Z-2E9W"

解释：字符串 S 被分成了两个部分，每部分 4 个字符；
     注意，两个额外的破折号需要删掉。
示例 2：

输入：S = "2-5g-3-J", K = 2

输出："2-5G-3J"

解释：字符串 S 被分成了 3 个部分，按照前面的规则描述，第一部分的字符可以少于给定的数量，其余部分皆为 2 个字符。
```

提示: S 的长度不超过 12,000，K 为正整数 S 只包含字母数字（a-z，A-Z，0-9）以及破折号'-' S 非空

方法：该题对空间占用限制比较严格，采用两个string来存储直接报错，采用一个string来存储，最后有可能第一个字符是‘-’，取substr也会超出限制，因此采用堆栈来存储，当string存的时候，stack刚好pop，因此不会超出限制，代码如下：

```
class Solution {
public:
    string licenseKeyFormatting(string S, int K) {
        stack<char>res;
        char tmp;
        int t=0;
        for(int i=S.length()-1;i>=0;i--)
        {
            
            if(t==K) 
            {
                res.push('-');
                t=0;
            }
            if(S[i]=='-') continue;
            tmp=S[i];
            if(tmp>96 && tmp <123) tmp-=32;
            res.push(tmp);
            t++;
           // cout<<res.top()<<endl;
        }
        //cout<<res.top()<<endl;
        if(!res.empty() && res.top()=='-')  res.pop();
        string ss;
        while(!res.empty())
        {
            ss+=res.top();
       //     cout<<ss<<endl;
            res.pop();
        }
        return ss;
        
    }
};
```

结果:

> 执行用时 : 20 ms, 在License Key Formatting的C++提交中击败了48.40% 的用户 内存消耗 : 11.1 MB, 在License Key Formatting的C++提交中击败了4.35% 的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/482.license_key_formatting.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
