当前位置:   article > 正文

动态规划---回文子串_回文子串构建

回文子串构建

1、题目:

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".

2、解答:若选择一个,则以它为中心,比较它左右的元素是否相等。若选择两个,则比较这两个元素,并比较它左右的元素是否相等。

3、代码

C++代码

  1. class Solution {
  2. public:
  3. int count = 0;
  4. int countSubstrings(string s) {
  5. if(s.length() == 0)
  6. return 0;
  7. for(int i=0;i<s.length();i++){
  8. extendPalindrome(s,i,i);        //选择一个中心点
  9. extendPalindrome(s,i,i+1);      //选择两个中心点  
  10. }
  11. return count;
  12. }
  13. void extendPalindrome(string s,int left,int right){
  14. while(left >= 0 && right < s.length() && s[left] == s[right]){
  15. count++;
  16. left--;
  17. right++;
  18. }
  19. }
  20. };

python代码的思路是:把该字符串的所有子串全部放在迭代器中。让后利用切片,判断是否相等

  1. class Solution:
  2. def countSubstrings(self, s):
  3. """
  4. :type s: str
  5. :rtype: int
  6. """
  7. def getAllSubstring(string):
  8. l = (string[x:y] for x in range(len(string)) for y in range(x+1,len(string)+1)) #生成一个迭代器[[a],[ab],[abc],[b],...]
  9. return l
  10. sub_y = lambda x : x == x[::-1]
  11. count = 0
  12. for i in getAllSubstring(s):
  13. if sub_y(i):
  14. count += 1
  15. return count

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/660199
推荐阅读
相关标签
  

闽ICP备14008679号