题目:
You are given a license key represented as a string
S
which consists only alphanumeric character and dashes. The string is separated intoN+1
groups byN
dashes.
Given a numberK
, we would want to reformat the strings such that each group contains exactlyK
characters, except for the first group which could be shorter thanK
, 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 stringS
and a numberK
, 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:
Thelength
of stringS
will not exceed12,000
, andK
is a positive integer.
StringS
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);