Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a Java problem of LeetCode Problem #294

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions Java/5-Longest_Palindromic_Substring.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
public class LongestPalindromicSubstring {

public String longestPalindrome(String s) {
// Update the string to put hash "#" at the beginning, end and in between each character
String updatedString = getUpdatedString(s);
// Length of the array that will store the window of palindromic substring
int length = 2 * s.length() + 1;
// Array to store the length of each palindrome centered at each element
int[] p = new int[length];
// Current center of the longest palindromic string
int c = 0;
// Right boundary of the longest palindromic string
int r = 0;
// Maximum length of the substring
int maxLength = 0;
// Position index
int position = -1;
for (int i = 0; i < length; i++) {
// Mirror of the current index
int mirror = 2 * c - i;
// Check if the mirror is outside the left boundary of current longest palindrome
if (i < r) {
p[i] = Math.min(r - i, p[mirror]);
}
// Indices of the characters to be compared
int a = i + (1 + p[i]);
int b = i - (1 + p[i]);
// Expand the window
while (a < length && b >= 0 && updatedString.charAt(a) == updatedString.charAt(b)) {
p[i]++;
a++;
b--;
}
// If the expanded palindrome is expanding beyond the right boundary of
// the current longest palindrome, then update c and r
if (i + p[i] > r) {
c = i;
r = i + p[i];
}
if (maxLength < p[i]) {
maxLength = p[i];
position = i;
}
}
int offset = p[position];
StringBuilder result = new StringBuilder();
for (int i = position - offset + 1; i <= position + offset - 1; i++) {
if (updatedString.charAt(i) != '#') {
result.append(updatedString.charAt(i));
}
}
return result.toString();
}

private String getUpdatedString(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
sb.append("#").append(s.charAt(i));
}
sb.append("#");
return sb.toString();
}
}
1 change: 1 addition & 0 deletions Java/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
### NOTE : Include the code in the list in order of leetcode problem statement number

1 : Two Sum<br>
5 : Longest Palindromic Substring<br>
7 : Reverse Integer<br>
9 : Palindrome Number<br>