482. License Key Formatting(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83542865

题目:

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:
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 isnon-empty.

解释:
重新格式化验证码。
python代码:

class Solution(object):
    def licenseKeyFormatting(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        S_upper=S.upper()
        str_S=''.join(S_upper.split('-'))
        if K==1:
            return '-'.join(str_S)
        result=''
        count=0
        i=len(str_S)
        while i>K:
            result=str_S[i-K:i]+result
            result='-'+result
            i-=K
            count+=K
        result=str_S[0:len(str_S)-count]+result
        return result   

c++代码:

#include <algorithm>
using namespace std;
class Solution {
public:
    string licenseKeyFormatting(string S, int K) {
        transform(S.begin(),S.end(),S.begin(),::toupper);
        S.erase(remove(S.begin(),S.end(),'-'),S.end());
        int i=S.size();
        string result="";
        int count=0;
        while(i>K)
        {
            result="-"+S.substr(i-K,K)+result;
            i-=K;
            count+=K;  
        }
        result=S.substr(0,S.size()-count)+result;
        return result;        
    }
};

总结:
c++删除字符串中的某个值:
vec.erase( remove(vec.begin(), vec.end(), 'A'), vec.end() )
remove的时候只是通过迭代器的指针向前移动来删除,将没有被删除的元素放在链表的前面,并返回一个指向新的超尾值的迭代器。由于remove()函数不是vector成员函数,因此不能调整vector容器的长度。(对vector来说)remove()函数并不是真正的删除,要想真正删除元素则可以使用erase()或者resize()函数。erase()函数可以删除给定区间的元素。它接受两个迭代器参数,这些参数规定了要删除的区间。例如:
score.erase(scores.begin(),score.begin()+2);

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83542865
今日推荐