Problem:
Given a string, return the longest substring that appears at both the beginning and end of the string without overlapping. For example, sameEnds("abXab") is "ab".
sameEnds("abXYab") → "ab"
sameEnds("xx") → "x"
sameEnds("xxx") → "x"
Solution:
public String sameEnds(String string) { int len = string.length(); String fin = ""; String tmp = ""; for (int i = 0; i < len; i++) { tmp += string.charAt(i); int tmplen = tmp.length(); if (i < len / 2 && tmp.equals(string.substring(len-tmplen,len))) fin = tmp; } return fin; }
Good job. My solution was similar:
ReplyDeletepublic String sameEnds(String string) {
for(int i=string.length()/2;i>=0;i--) {
String r=string.substring(0,i);
if(string.endsWith(r))return r;
}
return "";
}