当前位置:网站首页>LeetCode - 5 最长回文子串
LeetCode - 5 最长回文子串
2022-07-03 09:20:00 【三岁就很萌@D】
动态规划
class Solution {
public String longestPalindrome(String s) {
int n = s.length();
boolean[][] dp = new boolean[n][n];
int len = 0;
String ans = "";
for(int i = n-1; i >=0;i--){
for(int j = i; j < n;j++){
if(j == i){
dp[i][j] = true;
}
else if(j - i == 1){
dp[i][j] = s.charAt(i) == s.charAt(j);
}
else{
dp[i][j] = s.charAt(i) == s.charAt(j) && dp[i+1][j-1];
}
if(dp[i][j] == true){
if(j-i+1 > len){
len = j-i+1;
ans = s.substring(i,j+1);
}
}
}
}
return ans;
}
}
中心扩散
class Solution {
int len = 0;
String ans = "";
public String longestPalindrome(String s) {
int n = s.length();
for(int i = 0; i<n;i++){
centerSpread(s,i,i);
if(i < n-1)
centerSpread(s,i,i+1);
}
return ans;
}
public void centerSpread(String s,int left,int right){
int n = s.length();
int i = left;
int j = right;
while(i>=0 && j<n && s.charAt(i) == s.charAt(j))
{
i--;
j++;
}
if(j-i-1 > len){
len = j-i-1;
ans = s.substring(i+1,j);
}
}
}
边栏推荐
- Application of external interrupts
- QT is a method of batch modifying the style of a certain type of control after naming the control
- 2. Elment UI date selector formatting problem
- Yocto technology sharing phase IV: customize and add software package support
- STM32 general timer 1s delay to realize LED flashing
- 03 FastJson 解决循环引用
- 使用密钥对的形式连接阿里云服务器
- RESNET code details
- JS foundation - prototype prototype chain and macro task / micro task / event mechanism
- Gpiof6, 7, 8 configuration
猜你喜欢
Uniapp realizes global sharing of wechat applet and custom sharing button style
2. Elment UI date selector formatting problem
In third tier cities and counties, it is difficult to get 10K after graduation
Assignment to '*' form incompatible pointer type 'linkstack' {aka '*'} problem solving
Crash工具基本使用及实战分享
Opencv Harris corner detection
openEuler kernel 技术分享 - 第1期 - kdump 基本原理、使用及案例介绍
Octave instructions
2.Elment Ui 日期选择器 格式化问题
STM32 interrupt switch
随机推荐
Opencv feature extraction - hog
(2) New methods in the interface
Opencv interview guide
Stm32 NVIC interrupt priority management
After clicking the Save button, you can only click it once
Screen display of charging pile design -- led driver ta6932
Basic knowledge of MySQL database (an introduction to systematization)
4G module at command communication package interface designed by charging pile
Assignment to '*' form incompatible pointer type 'linkstack' {aka '*'} problem solving
03 FastJson 解决循环引用
自動裝箱與拆箱了解嗎?原理是什麼?
getopt_ Typical use of long function
byte alignment
2021-10-27
Leetcode 300 longest ascending subsequence
About windows and layout
Crash工具基本使用及实战分享
03 fastjason solves circular references
Blue Bridge Cup for migrant workers majoring in electronic information engineering
El table X-axis direction (horizontal) scroll bar slides to the right by default