Leet Code 5 Longest Palindromic Substring

2024-06-15 08:58

本文主要是介绍Leet Code 5 Longest Palindromic Substring,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.


【算法思路】

1. 最简单的办法就是以i为中心进行扩展回文,分奇数和偶数两种情况。O(n^2)


public class Solution {public String longestPalindrome(String s) {int length = s.length();if(length <= 1)return s;String longest = s.substring(0,1);for(int i = 0; i < length-1; i ++){String p1 = expandAroundCenter(s, i, i);if (p1.length() > longest.length())longest = p1;String p2 = expandAroundCenter(s, i, i+1);if (p2.length() > longest.length())longest = p2;}return longest;}String expandAroundCenter(String s, int c1, int c2) {int left = c1, right = c2;int n = s.length();while (left >= 0 && right <= n-1 && s.charAt(left) == s.charAt(right)) {left--;right++;}return s.substring(left+1, right);}
}


2. O(n)解法。相当巧妙,http://www.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html


定义函数
P[i,j] = 字符串区间[i,j]是否为palindrome.

首先找个例子,比如S="abccb",
    S=    a  b  c  c  b
Index = 0  1  2  3  4

P[0,0] =1  //each char is a palindrome
P[0,1] =S[0] == S[1] , P[1,1] =1 
P[0,2] = S[0] == S[2] && P[1,1], P[1,2] = S[1] == S[2] , P[2,2] = 1
P[0,3] = S[0] == S[3] && P[1,2], P[1,3] = S[1] == S[3] && P[2,2] , P[2,3] =S[2] ==S[3],  P[3,3]=1       
......................
由此就可以推导出规律

P[i,j] = 1  if i ==j
        =  S[i] ==S[j]   if j = i+1
        =  S[i] == S[j] && P[i+1][j-1]  if j>i+1

【CODE】

1:       string longestPalindrome(string s) {  
2:            int len = s.size();  
3:            int P[len][len];  
4:            memset(P, 0, len*len*sizeof(int));  
5:            int maxL=0, start=0, end=0;  
6:            for(int i =0; i< s.size(); i++)  
7:            {  
8:                 for(int j =0; j<i; j++)  
9:                 {  
10:                      P[j][i] = (s[j] == s[i] && (i-j<2 || P[j+1][i-1]));  
11:                      if(P[j][i] && maxL < (i-j+1))  
12:                      {  
13:                           maxL = i-j+1;  
14:                           start = j;  
15:                           end = i;  
16:                      }  
17:                 }  
18:                 P[i][i] =1;  
19:            }  
20:            return s.substr(start, end-start +1);  
21:       }  



这篇关于Leet Code 5 Longest Palindromic Substring的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1062998

相关文章

usaco 1.2 Palindromic Squares(进制转化)

考察进制转化 注意一些细节就可以了 直接上代码: /*ID: who jayLANG: C++TASK: palsquare*/#include<stdio.h>int x[20],xlen,y[20],ylen,B;void change(int n){int m;m=n;xlen=0;while(m){x[++xlen]=m%B;m/=B;}m=n*n;ylen=0;whi

Debugging Lua Project created in Cocos Code IDE creates “Waiting for debugger to connect” in Win-7

转自 I Installed Cocos Code IDE and created a new Lua Project. When Debugging the Project(F11) the game window pops up and gives me the message waiting for debugger to connect and then freezes. Also a

LLVM入门2:如何基于自己的代码生成IR-LLVM IR code generation实例介绍

概述 本节将通过一个简单的例子来介绍如何生成llvm IR,以Kaleidoscope IR中的例子为例,我们基于LLVM接口构建一个简单的编译器,实现简单的语句解析并转化为LLVM IR,生成对应的LLVM IR部分,代码如下,文件名为toy.cpp,先给出代码,后面会详细介绍每一步分代码: #include "llvm/ADT/APFloat.h"#include "llvm/ADT/S

VS Code 调试go程序的相关配置说明

用 VS code 调试Go程序需要在.vscode/launch.json文件中增加如下配置:  // launch.json{// Use IntelliSense to learn about possible attributes.// Hover to view descriptions of existing attributes.// For more information,

(nyoj308)substring

Substring 时间限制: 1000 ms  |  内存限制: 65535 KB 难度: 1 描述 You are given a string input. You are to find the longest substring of input such that the reversal of the substring is also a substring of

code: 400, msg: Required request body is missing 错误解决

引起这个错误的原因是,请求参数按照get方式给。 应该给json字符串才对 补充: 1. @RequestBody String resource 加@RequestBody必须给json字符串,否则会报错400,记如标题错误。 不加这个的进行请求的话,其实post和get就没有什么区别了。 2. List<String> indexCodes=(List<String>)json.

leetcode#32. Longest Valid Parentheses

题目 Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", wh

iOS项目发布提交出现invalid code signing entitlements错误。

1、进入开发者账号,选择App IDs,找到自己项目对应的AppId,点击进去编辑, 2、看下错误提示出现  --Specifically, value "CVYZ6723728.*" for key "com.apple.developer.ubiquity-container-identifiers" in XX is not supported.-- 这样的错误提示 将ubiquity

解决服务器VS Code中Jupyter突然崩溃的问题

问题 本来在服务器Anaconda的Python环境里装其他的包,装完了想在Jupyter里写代码验证一下有没有装好,一运行发现Jupyter崩溃了!?报错如下所示 Failed to start the Kernel. ImportError: /home/hujh/anaconda3/envs/mia/lib/python3.12/lib-dynload/_sqlite3.cpython-

MySQL中的`SUBSTRING()`和`MID()`函数:精准抽取字符串中的子串

在数据库操作中,经常需要从存储的字符串中提取出特定的部分,比如从用户全名中提取姓氏、从日期字符串中提取年份等。MySQL提供了SUBSTRING()和MID()两个函数,它们的功能几乎完全相同,都是用来从字符串中抽取子串的。本文将详细介绍这两个函数的用法、参数以及在实际场景中的应用。 一、SUBSTRING()和MID()函数的基本语法 1. SUBSTRING()函数 SUBSTRING(