0%

license-key-formatting

License Key Formatting – LeetCode 482

Problem

Description

GYou 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.iven two binary strings, return their sum (also a binary string).

Example

Input: S = “5F3Z-2e-9-w”, K = 4

Output: “5F3Z-2E9W”

Answer

Original

Code

1
2
3
4
5
6
7
8
9
class Solution {
public:
string licenseKeyFormatting(string S, int K) {
string res;
for (auto i = S.rbegin(); i < S.rend(); i++)
if (*i != '-') (res.size()%(K+1)-K? res : res+='-') += toupper(*i);
return reverse(res.begin(), res.end()), res;
}
};

思路

简单的构造然后倒置。时间复杂度$O(n)$,空间复杂度$O(1)$。
耗时$13$ ms,排名$27.59\%$

Better

思路

还没看到更好的思路。