-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongPalSub.java
More file actions
69 lines (58 loc) · 1.77 KB
/
longPalSub.java
File metadata and controls
69 lines (58 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.util.*;
class longPalSub {
public static String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int left = i, right = i;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
if (right - left >= end - start) { // Check if longest pal
start = left;
end = right;
}
left --;
right ++;
}
// Even-length pali
left = i;
right = i + 1;
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
if (right - left >= end - start) {
start = left;
end = right;
}
left --;
right ++;
}
}
return s.substring(start, end + 1);
}
public static void main(String[] args) {
String s1 = "abcdefedc";
System.out.println(longestPalindrome(s1));
System.out.println();
String s2 = "abrbadaadab";
System.out.println(longestPalindrome(s2));
}
}
/*
Longest Palindromic Substring
https://leetcode.com/problems/longest-palindromic-substring/description/
Given a string s, return the longest palindromic substring in s.
s in string babad
prev2=b
prev1=a
longest= s[n]= add to array, if i hit a letter in the array, it has to reverse
ba, b = bab
baba not pal, so still bab
babad, not pal, so still bab
need to calc length of palin
abcdefedc => cdefedc
Example 1:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd"
Output: "bb"
*/