Last active
March 22, 2022 11:04
-
-
Save sshaplygin/bce369822ef3495818e85e158fc1814b to your computer and use it in GitHub Desktop.
hw02_unpack_string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hw02unpackstring | |
import ( | |
"errors" | |
"strconv" | |
"strings" | |
"unicode" | |
) | |
const escapeSymbol string = "\\" | |
var ErrInvalidString = errors.New("invalid string") | |
func Unpack(inputString string) (string, error) { | |
var resultBuilder strings.Builder | |
var targetToRepeat string | |
var nextSymbolEscaped bool | |
for _, symbolRune := range inputString { | |
currentSymbol := string(symbolRune) | |
switch { | |
case nextSymbolEscaped: | |
if !(unicode.IsDigit(symbolRune) || currentSymbol == escapeSymbol) { | |
return "", ErrInvalidString | |
} | |
targetToRepeat = currentSymbol | |
nextSymbolEscaped = false | |
case currentSymbol == escapeSymbol: | |
resultBuilder.WriteString(targetToRepeat) | |
targetToRepeat = "" | |
nextSymbolEscaped = true | |
case unicode.IsDigit(symbolRune): | |
if targetToRepeat == "" { | |
return "", ErrInvalidString | |
} | |
repeatCount, err := strconv.Atoi(currentSymbol) | |
if err != nil { | |
return "", err | |
} | |
resultBuilder.WriteString(strings.Repeat(targetToRepeat, repeatCount)) | |
targetToRepeat = "" | |
default: | |
resultBuilder.WriteString(targetToRepeat) | |
targetToRepeat = currentSymbol | |
} | |
} | |
if nextSymbolEscaped { | |
return "", ErrInvalidString | |
} | |
resultBuilder.WriteString(targetToRepeat) | |
return resultBuilder.String(), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment