647. Palindromic Substrings
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc" Output: 3 Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa" Output: 6 Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
- The input string length won't exceed 1000.
题目含义:找出一个字符串中所有可能出现的回文子串的个数
方法一:像水的波纹一样,从两个位置(ij)开始依次往外扩散,直到不符合回文为止
1 private int count; 2 3 //找到以i,j为中心,往外扩散能构成的回文串个数 4 private void checkPalindrome(String s, int i, int j) { 5 while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){ //Check for the palindrome string 6 count++; //Increment the count if palindromin substring found 7 i--; //To trace string in left direction 8 j++; //To trace string in right direction 9 } 10 } 11 12 public int countSubstrings(String s) { 13 if (s.length()==0) return 0; 14 for (int i=0;i<s.length();i++) 15 { 16 checkPalindrome(s,i,i); 17 checkPalindrome(s,i,i+1); 18 } 19 return count; 20 }
方法二:dp[len][len] 代表[i,j]之间是否构成回文字符串
1 public int countSubstrings(String s) { 2 if(s == null || s.length() == 0) 3 return 0; 4 int len = s.length(); 5 int res = 0; 6 boolean[][] dp = new boolean[len][len]; //代表[i,j]之间是否构成回文字符串 7 for(int i = len - 1; i >= 0; i--){ 8 for(int j = i; j < len; j++){ 9 //首先i和j位置上的字符要相等 ,其次i和j的距离不超过2,如果超过2了,则要求[i+1,j-1]能构成回文串 10 if(s.charAt(i) == s.charAt(j) && (j - i <= 2 || dp[i + 1][j - 1])){ 11 dp[i][j] = true; 12 res++; 13 } 14 } 15 } 16 return res; 17 }
分类:
leetcode_dp
, leetcode_string
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!