aboutsummaryrefslogtreecommitdiff
path: root/LongestPalindrome.java
diff options
context:
space:
mode:
authorMichael Hunteman <michael@michaelted.xyz>2022-09-22 10:14:04 -0500
committerMichael Hunteman <michael@michaelted.xyz>2022-09-22 10:14:04 -0500
commit6522012065712fb0ece31bff9ff10b38a83b10e1 (patch)
tree743f3c13d08be9f60bad57b74e7a1fe7cc675e89 /LongestPalindrome.java
Initial commit
Diffstat (limited to 'LongestPalindrome.java')
-rw-r--r--LongestPalindrome.java55
1 files changed, 55 insertions, 0 deletions
diff --git a/LongestPalindrome.java b/LongestPalindrome.java
new file mode 100644
index 0000000..447bb27
--- /dev/null
+++ b/LongestPalindrome.java
@@ -0,0 +1,55 @@
+import java.lang.*;
+import java.util.*;
+
+class LongestPalindrome {
+ public static String longestPalindrome(String s) {
+ // TODO: check if s length is 0 or 1
+ // TODO: find simpler solution
+
+ s = s.toLowerCase();
+ char[] arr = s.toCharArray();
+ String ans = null;
+
+ int i = 0;
+ int j = 0;
+ int max = 0;
+ // Odd case: "aba"
+ for (int a = 1; a < arr.length - 1; a++) {
+ i = a - 1;
+ j = a + 1;
+ while (i >= 0 && j < arr.length) {
+ if (arr[i] == arr[j]) {
+ if (j - i > max) {
+ max = j - i;
+ ans = s.substring(i, j + 1);
+ }
+ i--;
+ j++;
+ } else {
+ break;
+ }
+ }
+ }
+ // Even case: "abba"
+ for (i = 0, j = i + 1; i < arr.length - 1; i++) {
+ while (i >= 0 && j < arr.length) {
+ if (arr[i] == arr[j]) {
+ if (j - i > max) {
+ max = j - i;
+ ans = s.substring(i, j + 1);
+ }
+ i--;
+ j++;
+ } else {
+ break;
+ }
+ }
+ }
+ return ans;
+ }
+
+ public static void main(String[] args) {
+ String s = "kl;fadsjf;dalscbbciuporeqwrpo";
+ System.out.println(longestPalindrome(s));
+ }
+}