Solution 1 - Reverse Build (Group from End)
Remove dashes, uppercase, then build groups of size k from right to left.
Remove dashes, uppercase, then build groups of size k from right to left.
""" 0482.1 - License Key Formatting - Solution 1 - Reverse Build """
class Solution:
def licenseKeyFormatting(self, s: str, k: int) -> str:
cleaned = s.replace("-", "").upper()
out = []
cnt = 0
for ch in reversed(cleaned):
if cnt == k:
out.append("-")
cnt = 0
out.append(ch)
cnt += 1
return "".join(reversed(out))
if __name__ == "__main__":
print(Solution().licenseKeyFormatting("5F3Z-2e-9-w", 4)) # 5F3Z-2E9Wpackage main
import "strings"
func licenseKeyFormatting(s string, k int) string {
cleaned := strings.ToUpper(strings.ReplaceAll(s, "-", ""))
out := make([]byte, 0, len(cleaned)+len(cleaned)/k)
cnt := 0
for i := len(cleaned) - 1; i >= 0; i-- {
if cnt == k {
out = append(out, '-')
cnt = 0
}
out = append(out, cleaned[i])
cnt++
}
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
return string(out)
}
func main() {}