Codility and other programming lessons: Lesson 99: StrSymmetryPoint (Str Symmetry Point)
Write a function:
int solution(char *S);
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.
This is a simple problem. We only scan from both ends.
If the scanning positions reached the same position, that's the
answer.
int solution(char *S) {
int len = strlen(S);
if (len % 2 == 0){
return -1;
}
int l = 0;
int r = len - 1;
while (l < r){
if (S[l] != S[r]){
return -1;
}
l++;
r--;
}
return l;
}
http://codilitysolutions.blogspot.com/2015/06/future-training-strsymmetrypoint.html
08 | public int solution(String S) { |
10 |
11 | if (S.length() == 1 ) return 0 ; |
|
12 | else if (S.length() == 0 || S.length() % 2 == 0 ) return - 1 ; |
16 | for ( int i = 0 ; i < half; i++) { |
17 | if (S.charAt(i) != S.charAt((len - 1 ) - i)) return - 1 ; |
http://www.martinkysel.com/codility-str-symmetry-point-solution/
def
solution(S):
l
=
len
(S)
if
l
%
2
=
=
0
:
return
-
1
mid_point
=
l
/
/
2
for
idx
in
xrange
(
0
, mid_point):
if
S[idx] !
=
S[l
-
idx
-
1
]:
return
-
1
return
mid_point
Read full article from
Codility and other programming lessons: Lesson 99: StrSymmetryPoint (Str Symmetry Point)