Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codingbat challenge: sameEnds

Given task sameEnds from CodingBat:

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"

My solution passes all the tests except one^:

public String sameEnds(String string) {
  String substringFront = "";
  String substringEnd = "";
  String longestSubstring = "";
  
  for (int i = 1; i < string.length() - 1; i++) {
    substringFront = string.substring(0, i);
    substringEnd = string.substring(i);
    
    if (substringEnd.contains(substringFront)) {
      longestSubstring = substringFront;
    }
  }
  
  return longestSubstring;
}

What is the problem here? How could I fix it?

enter image description here

like image 373
Evgeniy Avatar asked Jan 23 '26 21:01

Evgeniy


1 Answers

In addition to the technical issues that @Dan and others have aptly pointed out, I want to highlight the issue of unnecessary complexity, which in many cases leads to such logical errors.

Given this, and considering that this is a challenge, I would prefer a minimalistic approach, like the one below, which is self-explanatory and hence simple to comprehend and debug.

public String sameEnds(String string) {
  int middle = string.length() / 2;
  for (int i = middle; i >= 0; i--) {
    String left = string.substring(0, i);
    if (string.endsWith(left)) {
      return left;
    }
  }
  return "";
}
like image 81
Andreas Violaris Avatar answered Jan 25 '26 11:01

Andreas Violaris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!