5 minutes for Java
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.
Task:
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.
Example:
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))) { result.append(symbol); } else { break; } } return result.toString(); }
Try to solve this exercise by yourself. It will be great to see more efficient solution in the comments.