Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Title Description:

482. Key formatting

Given a license key string S, consisting of only alphanumeric characters and dashes. The string consists of n dashes divided into n + 1 groups. You also get an integer k.

We want to reformat the string S so that each group contains K characters, except for the first group, which can be shorter than K but still must contain at least one character. In addition, dashes must be inserted between groups, and all lowercase letters should be converted to uppercase letters.

Returns the reformatted license key.

Example 1:

Input: S = "5f3z-2e-9-w ", k = 4 Output:" 5F3Z-2e9w "Explanation: The string S is split into two parts, each of which contains four characters; Note that the two extra dashes need to be deleted.Copy the code

Example 2:

Input: S = "2-5g-3-j ", k = 2 Output:" 2-5g-3j"Copy the code

Tip:

  • 1 <= s.length <= 10^5
  • The s contains only letters, digits, and dashes ‘-‘.
  • 1 <= k <= 10^4

Ii. Analysis of Ideas:

  • Replace “-” with “” using the ReplaceAll function, removing” -“
  • Use the ToUpper function to convert all lowercase letters to uppercase
  • If the string length n is a multiple of k, i.e. N %k==0, append k characters from the string, followed by “-“
  • If n % k! =0, then the first append only needs to fetch the first N % K characters from the string, followed by “-“, and then k more
  • And finally get rid of the trailing “-“

Iii. AC Code:

func licenseKeyFormatting(s string, k int) string {
	ss := strings.ToUpper(strings.ReplaceAll(s, "-".""))
	n := len(ss)
	var ans []byte
	ifn % k ! =0{ ans = append(append(ans, ss[:n%k]...) .The '-')}fori := n%k; i < n; i+=k { ans = append(append(ans, ss[i:i+k]...) .The '-')}if len(ans) > 0 && ans[len(ans)1]= =The '-' {
		ans = ans[:len(ans)-1]}return string(ans)
}
Copy the code