1. 程式人生 > >leetcode-482-License Key Formatting

leetcode-482-License Key Formatting

exactly you mis rac des sub har 插入 rules

題目描述:

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.

要完成的函數:

string licenseKeyFormatting(string S, int K)

說明:

1、給定一個字符串S和一個正數K,字符串中只含有字母、數字和破折號,比如5F3Z-2e-9-w。

要求將字符串的格式重新編排,使得被破折號隔開的每個部分含有K個字符,除了最開始的第一個部分可以是小於等於K個字符的,但必須至少有一個字符。

同時要求字符串中的小寫字母轉化為大寫字母。

比如字符串是5F3Z-2e-9-w,K=4,那麽重新編排完格式是5F3Z-2E9W。

如果字符串是9-5F3Z-2e-9-w,K=4,那麽重新編排完格式就是9-5F3Z-2E9W。

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;
    }

上述代碼實測12ms,beats 98.58% of cpp submissions。

3、一些其他說明:

可能有的同學寫的也是跟筆者一樣的2中的代碼,只不過在res+=char(toupper(S[i]))這裏,改成了res=char(toupper(S[i]))+res。這樣最後就不用reverse了。

但這樣提交了之後會發現花費時間巨大,是2中代碼花費時間的20倍左右。

原因是res=char(toupper(S[i]))+res處理的時候,可以看做是重新定義一個臨時字符串,把S[I]的值放進去,然後再增加了res,最後把臨時字符串賦給了res。

而res+=char(toupper(S[i]))是直接在res後面增加了S[i],類似於vector.push_back()。

兩者相比較起來,還是2中的方法快速,最後做一下reverse其實花費時間也不多。

leetcode-482-License Key Formatting