[LeetCode] License Key Formatting 註冊碼格式化
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.
Example 1:
Input: S = "2-4A0r7-4k", K = 4 Output: "24A0-R74K" Explanation: The string S has been split into two parts, each part has 4 characters.
Example 2:
Input: S = "2-4A0r7-4k", K = 3 Output: "24-A0R-74K" Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said 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.
這道題讓我們對註冊碼進行格式化,正確的註冊碼的格式是每四個字元後面跟一個短槓,每一部分的長度為K,第一部分長度可以小於K,另外,字母必須是大寫的。那麼由於第一部分可以不為K,那麼我們可以反過來想,我們從S的尾部往前遍歷,把字元加入結果res,每K個後面加一個短槓,那麼最後遍歷完再把res翻轉一下即可,注意翻轉之前要把結尾的短槓去掉(如果有的話),參見程式碼如下:
解法一:
class Solution { public: string licenseKeyFormatting(string S, int K) { string res = ""; int cnt = 0, n = S.size(); for (int i = n - 1; i >= 0; --i) { char c = S[i]; if (c == '-') continue; if (c >= 'a' && c <= 'z') c -= 32; res.push_back(c); if (++cnt % K == 0) res.push_back('-'); } if (!res.empty() && res.back() == '-') res.pop_back(); return string(res.rbegin(), res.rend()); } };
上面程式碼可以進一步精簡到下面這種,我們用到了自帶函式toupper,把字母轉為大寫格式,參見程式碼如下:
解法二:
class Solution { public: string licenseKeyFormatting(string S, int K) { string res = ""; for (int i = (int)S.size() - 1; i >= 0; --i) { if (S[i] != '-') { ((res.size() % (K + 1) - K) ? res : res += '-') += toupper(S[i]); } } return string(res.rbegin(), res.rend()); } };
參考資料: