问题描述:
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.
Note:
- The length of string S will not exceed 12,000, and K is a positive integer.
- String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
- String S is non-empty.
利用C++和Java两种语言进行编程
C++中会用到如下string的函数
- push_back(c):将元素添加到该字符串的末尾
- empty():当前字符串是否为空
- at(i):返回字符串下标为i处的字符的引用
- back():返回字符串最后一个字符的引用
- front():返回字符串第一个字符的引用
- pop_back():删除字符串的最后一个字符
- rbegin():返回一个逆向迭代器,指向字符串的最后一个字符
- rend():返回一个逆向迭代器,指向字符串的开头(第一个字符的前一个位置)。
C++:
class Solution {
public:
string licenseKeyFormatting(string S, int K) {
string res = "";
int len = S.size();
int count = 0;
for (int i = len - 1; i >= 0; i--) {
char c = S[i];
if (c == '-') continue;
if (c >= 'a' && c <= 'z') c -= 32;
res.push_back(c);
count++;
if (count % K == 0)
{
res.push_back('-');
}
}
if (!res.empty() && res.back() == '-')
res.pop_back();
return string(res.rbegin(), res.rend());
}
};
Java:
class Solution {
public String licenseKeyFormatting(String S, int K) {
StringBuilder sb = new StringBuilder();
for(int i = S.length() - 1; i >= 0; i--){
if(S.charAt(i) != '-')
sb.append(sb.length() % (K + 1) == K ? '-' : "").append(S.charAt(i));
}
return sb.reverse().toString().toUpperCase();
}
}