Skip to content

Instantly share code, notes, and snippets.

@FreddieLindsey
Created January 16, 2016 07:22
Show Gist options
  • Save FreddieLindsey/efbbfee56d315615b04b to your computer and use it in GitHub Desktop.
Save FreddieLindsey/efbbfee56d315615b04b to your computer and use it in GitHub Desktop.
Finds the most common palindrome in a string
import javafx.util.Pair;
import java.util.HashMap;
import java.util.Map;
public class MostCommonPalindrome {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: <program> <string_to_find_palindromes>");
System.exit(1);
}
String s = args[0];
Pair<String, Integer> result = findCommonPalindrome(s);
if (result.getValue() == 0) {
System.out.println("No palindrome found");
} else {
System.out.println("Found:\t" + result.getKey() + " " + result.getValue() + " times.");
}
}
private static Pair<String, Integer> findCommonPalindrome(String s) {
Map<String, Integer> foundPalindromes = new HashMap<>();
Pair<String, Integer> maxPalindrome = new Pair<>("string", 0);
for (int i = 0; i < s.length() - 1; i++) {
for (int j = i + 1; j < s.length(); j++) {
if (verifyPalindrome(s, i, j)) {
String substring = s.substring(i, j + 1);
Integer foundTimes = foundPalindromes.get(substring);
if (foundTimes == null) {
foundTimes = 0;
}
foundTimes++;
foundPalindromes.put(substring, foundTimes);
if (maxPalindrome == null || maxPalindrome.getValue() < foundTimes) {
maxPalindrome = new Pair<>(substring, foundTimes);
}
}
}
}
return maxPalindrome;
}
private static boolean verifyPalindrome(String s, int start, int end) {
int length = end - start + 1;
for (int i = start; i <= start + (length / 2); i++) {
if (s.charAt(i) != s.charAt(end - (i - start))) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment