https://leetcode-cn.com/problems/license-key-formatting/
快
class Solution:
def licenseKeyFormatting(self, S: str, K: int) -> str:
NewS = ''
for i in range(len(S)):
if S[i] !='-':
NewS+=S[i]
Left = len(NewS)%K
R = ''
if Left!=0:
for i in range(Left):
R+=self.upper(NewS[i])
R += '-'
NewS = NewS[Left:]
for i in range(len(NewS)):
R+=self.upper(NewS[i])
if (i+1)%K == 0:
R += '-'
return R[:-1]
def upper(self,s):
if ord(s) <= ord('z') and ord(s) >= ord('a'):
return chr(ord(s) - ord('a') + ord('A'))
else:
return s
慢
class Solution:
def licenseKeyFormatting(self, S: str, K: int) -> str:
N = 0
L = len(S)
R = ''
for i in range(L):
if S[L-i-1] != '-':
N += 1
R = self.upper(S[L-i-1]) + R
if N%K == 0:
R = '-' + R
if len(R) ==0:
return ''
elif R[0] == '-':
return R[1:]
else:
return R
def upper(self,s):
if ord(s) <= ord('z') and ord(s) >= ord('a'):
return chr(ord(s) - ord('a') + ord('A'))
else:
return s