Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Create Longest Palindromic Subsequence#36

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
its-sai wants to merge1 commit intorampatra:master
base:master
Choose a base branch
Loading
fromits-sai:patch-1
Open
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
import java.util.*;
import java.io.*;

class home{
public static void main(String args[]){
Scanner sc= new Scanner (System.in);
int t=sc.nextInt();
while(t-->0){
String s=sc.next();
Solution obj = new Solution();
System.out.println(obj.longestPalinSubseq(s);
}
}
}

class Solution
{
public int longestPalinSubseq(String A)
{

int n = A.length();

StringBuilder st = new StringBuilder();
st.append(A);
st.reverse();

String B = st.toString();

// a palindrome reads the same from front and reverse.
// hence, the longest palindromic subsequence is
// basically the longest common subsequence in
// A and reverse(A)
int[][] dp = new int[n + 1][n + 1];
for (int i = 0; i <= n; ++i)
{
for (int j = 0; j <= n; ++j)
{
if (i == 0 || j == 0)
dp[i][j] = 0;
else
{
if (A.charAt(i - 1) == B.charAt(j - 1))
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = Math.max (dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[n][n];
}
}

[8]ページ先頭

©2009-2025 Movatter.jp