Archive

Archive for July, 2017

How To Find Longest Palindrome In String

July 29, 2017 Leave a comment

Below is code to find longest palindrome in string.


public class Palindrome {

public String getLongestPalindrome(String words) {
String longest = words.substring(0, 1);
for (int i = 0; i < words.length(); i++) {
String temp = helper(words, i, i);
if (longest.length() < temp.length()) {
longest = temp;
}

temp = helper(words, i, i + 1);
if (longest.length() < temp.length()) {
longest = temp;
}
}
return longest;
}

private String helper(String words,int left, int right) {
while (left >= 0 && right < words.length()&& words.charAt(left) == words.charAt(right)) {
left--;
right++;
}
return words.substring(left + 1, right);
}
}

🙂

Advertisements