This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashSet; | |
import java.util.Set; | |
/** | |
* Created by panded4 | |
*/ | |
public class Palindrome2 { | |
public static Set<String> palindromes(final String input) { | |
final Set<String> result = new HashSet<>(); | |
for (int i = 0; i < input.length(); i++) { | |
// expanding even length palindromes: | |
expandPalindromes(result, input, i, i + 1); | |
// expanding odd length palindromes: | |
expandPalindromes(result, input, i, i); | |
} | |
return result; | |
} | |
public static void expandPalindromes(final Set<String> result, final String s, int i, int j) { | |
while (i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)) { | |
result.add(s.substring(i, j + 1)); | |
i--; | |
j++; | |
} | |
} | |
public static void main(String[] args) { | |
for (String set : palindromes("liiri")) { | |
System.out.println(set); | |
} | |
} | |
} |
No comments:
Post a Comment