Leetcode Note: Go - Reformat Phone Number
Reformat Phone Number - LeetCode
https://leetcode.com/problems/reformat-phone-number/
- Go 言語で取り組んだメモ
回答
Go solution using two approaches (0ms) - Reformat Phone Number - LeetCode
https://leetcode.com/problems/reformat-phone-number/solutions/1007037/go-solution-using-two-approaches-0ms/
func reformatNumber(number string) string {
chars := []byte(number)
cleanedChars := []byte{}
for _, char := range chars {
if char == ' ' || char == '-' {
continue
}
cleanedChars = append(cleanedChars, char)
}
resultChars := []byte{}
for i, char := range cleanedChars {
if i != 0 && i % 3 == 0 {
resultChars = append(resultChars, '-')
}
if i % 3 == 0 && (len(cleanedChars) - i == 2 || len(cleanedChars) - i == 3) {
resultChars = append(resultChars, cleanedChars[i:]...)
break
}
if i % 3 == 0 && len(cleanedChars) - i == 4 {
resultChars = append(resultChars, cleanedChars[i:i+2]...)
resultChars = append(resultChars, '-')
resultChars = append(resultChars, cleanedChars[i+2:]...)
break
}
resultChars = append(resultChars, char)
}
return string(resultChars)
}