当前位置:网站首页>力扣5: 最长回文子串
力扣5: 最长回文子串
2022-07-26 06:23:00 【weixin_54096215】
题目:回文子串(从左到右和从右到左的字符串一样)

思路:
1.假设会问字串的长度是1;
2.设定一个布尔类型的二维数组,使用两个指针i,j分别进行遍历其中i=0,j<=i;
3.判断,使用charAt()方法进行判断,两个字符串是否相等,而且它们的长度是否等于2
代码:
class Solution {
public String longestPalindrome(String s) {
// 特例判断
if(s.length() < 2 || s == null) return s;
int len = s.length(); // 字符串的长度
int start = 0; // 最长回文子串的起点
int end = 0; // 最长回文子串的终点
int max = 1; // 最长回文子串的长度
boolean[][] dp = new boolean[len][len];// 创建二维数组,用于存放状态
for(int i = 0; i < len; i++){
for(int j = 0; j <= i; j++){
if(s.charAt(j) == s.charAt(i) && (i-j < 2 || dp[j+1][i-1])){
dp[j][i] = true;
if(i-j+1 > max){
start = j;
end = i;
max = Math.max(max, i-j+1);
}
}
}
}
return s.substring(start, end+1);
}
}
细节:
charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
参考:
边栏推荐
- Leetcode:934. The shortest Bridge
- K. Link with Bracket Sequence I dp
- [nanny level] package volume optimization tutorial
- 将金额数字转换为大写
- 【Day_07 0425】合法括号序列判断
- 【pytorch】图片增广
- Swift basic FileManager (file management)
- If introduced according to the open source framework
- Matlab 向量与矩阵
- Concurrency opening -- take you from 0 to 1 to build the cornerstone of concurrency knowledge system
猜你喜欢

【Day05_0422】C语言选择题

Workflow activiti5.13 learning notes (I)

Code Runner for VS Code,下载量突破 4000 万!支持超过50种语言

RNN循环神经网络

A tool for quickly switching local host files -- switchhosts

Matlab 向量与矩阵

Easycvr video square channel display and video access full screen display style problem repair

Operating steps for uninstalling the mobile app

H. Take the elevator greedy

Understanding the mathematical essence of machine learning
随机推荐
[day_060423] no two
【pytorch】微调技术
YOLOv6:又快又准的目标检测框架开源啦
Implementation of PHP multitask second timer
Convolutional neural network (III) - target detection
BigDecimal becomes negative
【BM2 链表内指定区间反转】
What are the aspects of performance testing? What are the classification and testing methods?
性能测试包括哪些方面?分类及测试方法有哪些?
Xiao He shows his sharp corners and says hello to flutter app
【C语言】文件操作
[2023 Jerry technology approval test questions in advance] ~ questions and reference answers
A tool for quickly switching local host files -- switchhosts
Map collection inheritance structure
Upgrade appium automation framework to the latest 2.0
[day06_0423] C language multiple choice questions
[(SV & UVM) knowledge points encountered in written interview] ~ phase mechanism
Using dynamic libraries in VS
Workflow activiti5.13 learning notes (I)
What is spark serialization for?