回文子串
647:给你一个字符串 s,请你统计并返回这个字符串中 回文子串 的数目。
class Solution {
public int countSubstrings(String s) {
int length = s.length();
//s的区间[i,j]是否为回文串
boolean[][] dp = new boolean[length][length];
int res = 0;
//dp[i][j]依赖于dp[i+1][j-1],因此遍历顺序从下往上、从左往右
for(int i =length-1;i>=0;i--){
//j一定要大于等i
for(int j=i;j<length;j++){
//dp[length-1][length-1]这时候赋值为true,下面不会出现越界
if(s.charAt(i)==s.charAt(j)){
if(j-i<=1){
res++;
dp[i][j]=true;
}else if(dp[i+1][j-1]){
res++;
dp[i][j]=true;
}
}
}
}
return res;
}
}
最长回文字串
5:给你一个字符串 s,找到 s 中最长的回文子串。
class Solution {
public String longestPalindrome(String s) {
int length = s.length();
boolean[][] dp = new boolean[length][length];
int start = 0;
int end = 0;
for(int i=length-1;i>=0;i--){
for(int j=i;j<length;j++){
if(s.charAt(i)==s.charAt(j)){
if(j-i<2){
dp[i][j]=true;
}else{
dp[i][j] = dp[i+1][j-1];
}
}
if(dp[i][j]&&j-i>end-start){
start = i;
end = j;
}
}
}
return s.substring(start,end+1);
}
}
最长公共字串
给定两个字符串str1和str2,输出两个字符串的最长公共子串,题目保证str1和str2的最长公共子串存在且唯一。
public class Solution {
/**
* longest common substring
* @param str1 string字符串 the string
* @param str2 string字符串 the string
* @return string字符串
*/
public String LCS (String str1, String str2) {
// write code here
int m = str1.length();
int n = str2.length();
int[][] dp = new int[m+1][n+1];
int maxLen = 0;
int end =0;
for(int i =1; i<=m; i++){
for(int j=1; j<=n; j++){
if(str1.charAt(i-1)==str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1]+1;
}
if(dp[i][j]>maxLen){
end = i;
maxLen = dp[i][j];
}
}
}
return maxLen == 0 ? "" : str1.substring(end-maxLen,end);
}
}
最长公共子序列
leetcode 1143:给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列 的长度。如果不存在公共子序列 ,返回 0 。
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length()+1][text2.length()+1];
for(int i = 1; i<=text1.length(); i++){
for(int j =1; j<=text2.length(); j++){
if(text1.charAt(i-1)==text2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]);
}
}
}
return dp[text1.length()][text2.length()];
}
}
最长公共子序列II
给定两个字符串str1和str2,输出两个字符串的最长公共子序列。如果最长公共子序列为空,则返回 "-1"。目前给出的数据,仅仅会存在一个最长的公共子序列。
public class Solution {
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
public String LCS (String s1, String s2) {
// write code here
int m = s1.length();
int n = s2.length();
String[][] dp = new String[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
dp[i][j] = "";
} else if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + s1.charAt(i - 1);
} else {
dp[i][j] = dp[i - 1][j].length() > dp[i][j - 1].length() ? dp[i - 1][j] : dp[i][j - 1];
}
}
}
if(dp[m][n]==""){
return "-1";
}
return dp[m][n];
}
}