It’s time to publish new one java exercise. Today it will be related to working with strings, so prepare to solve a problem which you can meet on some java interview. A solution of the problem has no any restriction, you just have to write the optimal code.


Complete the method’s body public String subStringSearch(String str); The method must return the longest substring at the begin of str which has inverse analog in the end of str.


str = “abctrefcba”, returns: “abc”;
str = “rmmr”, returns: “rm”;
str = “asasfgh”, returns: “”;

Here is my solution:

	public String subStringSearch(String str) {
		StringBuilder result = new StringBuilder();

		int length = str.length();

		for (int i = 0; i < length / 2; i++) {
			char symbol = str.charAt(i);
			if (symbol == str.charAt(length - (i + 1))) {
			} else {
		return result.toString();

Try to solve this exercise by yourself. It will be great to see more efficient solution in the comments.

About The Author

Mathematician, programmer, wrestler, last action hero... Java / Scala architect, trainer, entrepreneur, author of this blog

  • totha

    In the case
    str = “rmmr”, returns: “rm”;
    Shouldn’t the whole string be returned (by leaving out the division by 2)?

    • Fruzenshtein

      It’s ok
      You should consider the problem from the point of view of symmetry