I decided to try out the recent code puzzler for finding the largest palindrome in a string. Here was my first method:
public static int getLargestPalindrome(String palindromes) { String[] palindromeArray = palindromes.split(" "); int largestPalindrome = -1; for(String potentialPalindrome : palindromeArray) { if (potentialPalindrome.equals(new StringBuffer(potentialPalindrome).reverse().toString()) && potentialPalindrome.length() > largestPalindrome) largestPalindrome = potentialPalindrome.length(); } return largestPalindrome; }
It works, but it felt like cheating to use the StringBuffer.reverse() method. Here is my second method:
public static int getLargestPalindrome(String palindromes) { int largestPalindrome = -1; for(String potentialPalindrome : palindromes.split(" ")) { int start = 0; int end = potentialPalindrome.length() - 1; boolean isPalindrome = true; while (start <= end) { if (potentialPalindrome.charAt(start++) != potentialPalindrome.charAt(end--)) { isPalindrome = false; break; } } if (isPalindrome && potentialPalindrome.length() > largestPalindrome) { largestPalindrome = potentialPalindrome.length(); } } return largestPalindrome; }
It works faster than the first method. I'm sure the performance improvement is mainly due to the first method's creation of new StringBuffer objects (and also new Strings for the reversed value) for each potential palindrome, but accessing locations in an array for half the length (worst case in 2nd version) is bound to be less work than (worst case in 1st version) comparing every character in a string to another string.
No comments:
Post a Comment