[Codility] StrSymmetryPoint (Go)
https://app.codility.com/programmers/trainings/4/str_symmetry_point/
StrSymmetryPoint coding task - Practice Coding - Codility
Find a symmetry point of a string, if any.
app.codility.com
Task description
Write a function:
func Solution(S string) int
that, given a string S, returns the index (counting from 0) of a character such that the part of the string to the left of that character is a reversal of the part of the string to its right. The function should return −1 if no such index exists.
Note: reversing an empty string (i.e. a string whose length is zero) gives an empty string.
For example, given a string:
"racecar"
the function should return 3, because the substring to the left of the character "e" at index 3 is "rac", and the one to the right is "car".
Given a string:
"x"
the function should return 0, because both substrings are empty.
Write an efficient algorithm for the following assumptions:
- the length of string S is within the range [0..2,000,000].
package solution
import "strings"
func Solution(S string) int {
var ln = len([]rune(S))
switch ln {
case 0:
return -1
case 1:
return 0
}
var mid = len([]rune(S)) / 2
if S[0:mid+1] != getReverserStr(mid, S) {
return -1
}
return mid
}
func getReverserStr(idx int, S string) string {
var result strings.Builder
for i := len([]rune(S)) - 1; i >= idx; i-- {
result.WriteString(S[i : i+1])
}
return result.String()
}