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

LongestpalindromicSubstring in Java and python #262

Open
wants to merge 2 commits 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
36 changes: 36 additions & 0 deletions Leetcode-Medium/5-LongestPalindromicSubstring/solutionInJava.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class Solution {
public String longestPalindrome(String s) {
char[] sChars = s.toCharArray();

int m = s.length();

// * dp[i][len + 1] means substring starting from i with length of len;
boolean[][] dp = new boolean[m][2];
int currCol = 0;

int maxLen = 0;
int ans = 0; // record start index of s

for (int len = 0; len < m; len++) {
for (int start = 0; start + len < m; start++) {
int end = start + len;
if (len == 0) {
dp[start][currCol] = true;
} else if (len == 1) {
dp[start][currCol] = (sChars[start] == sChars[end]);
} else {
dp[start][currCol] = (sChars[start] == sChars[end] && dp[start + 1][currCol]);
}

if (dp[start][currCol] && len + 1 > maxLen) {
ans = start;
maxLen = len + 1;
}
}

currCol = 1 - currCol;
}

return maxLen == 0 ? "" : s.substring(ans, ans + maxLen);
}
}
27 changes: 27 additions & 0 deletions Leetcode-Medium/5-LongestPalindromicSubstring/solutioninpython.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution:
def longestPalindrome(self, s: str) -> str:

n = len(s)
# Form a bottom-up dp 2d array
# dp[i][j] will be 'true' if the string from index i to j is a palindrome.
dp = [[False] * n for _ in range(n)]

ans = ''
# every string with one character is a palindrome
for i in range(n):
dp[i][i] = True
ans = s[i]

maxLen = 1
for start in range(n-1, -1, -1):
for end in range(start+1, n):
# palindrome condition
if s[start] == s[end]:
# if it's a two char. string or if the remaining string is a palindrome too
if end - start == 1 or dp[start+1][end-1]:
dp[start][end] = True
if maxLen < end - start + 1:
maxLen = end - start + 1
ans = s[start: end+ 1]

return ans
12 changes: 12 additions & 0 deletions Leetcode-Medium/946-validate-stack-sequences/solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int i = 0;
for (int x : pushed) {
stack.push(x);
while (!stack.empty() && stack.peek() == popped[i]) {
stack.pop();
i++;
}
}
return stack.empty();
}