482. License Key Formatting(python+cpp)
題目:
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);