Home > Java > How To Find Longest Palindrome In String

How To Find Longest Palindrome In String

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
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: