StrSymmetryPoint

Find a symmetry point of a string, if any
ℹ️ © Codility, 2009-2018

Problem

Write a function 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.

Assume that:
• the length of S is within the range [0 … 2,000,000].

Complexity:
• expected worst-case time complexity is O(length(S));
• expected worst-case space complexity is O(1) (not counting the storage required for input arguments).

Solution

C#

class Solution {
  public int solution(string S) {
    int n = S.Length;
    if (n % 2 == 0) {
      return -1;
    }
    int r = n / 2;
    for (int i = 0; i < r; i++) {
      if (S[i] != S[n - i - 1]) {
        return -1;
      }
    }
    return r;
  }
}

Java

class Solution {
  public int solution(String S) {
    int n = S.length();
    if (n % 2 == 0) {
      return -1;
    }
    int r = n / 2;
    for (int i = 0; i < r; i++) {
      if (S.charAt(i) != S.charAt(n - i - 1)) {
        return -1;
      }
    }
    return r;
  }
}

JavaScript

function solution(S) {
  let n = S.length;
  if (n % 2 == 0) {
    return -1;
  }
  let r = parseInt(n / 2);
  for (let i = 0; i < r; i++) {
    if (S[i] != S[n - i - 1]) {
      return -1;
    }
  }
  return r;
}

PHP

function solution($S) {
  $n = strlen($S);
  if ($n % 2 == 0) {
    return -1;
  }
  $r = intval($n / 2);
  for ($i = 0; $i < $r; $i++) {
    if ($S[$i] != $S[$n - $i - 1]) {
      return -1;
    }
  }
  return $r;
}