2018-05-25

题目

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:3Explanation:Three palindromic strings: "a", "b", "c".

Example 2:

Input:"aaa"Output:6Explanation:Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

The input string length won't exceed 1000.

解法

1. Extend palindrome

时间:O(n^2), 空间O(1)

'''
class Solution {
int count = 0;
public int countSubstrings(String s) {
if(s == null || s.length() == 0) return 0;
int n = s.length();
for(int i = 0; i < n; i++){
checkAdj(i, i, n, s);
checkAdj(i, i + 1, n, s);
}
return count;
}

public void checkAdj(int start, int end, int n, String s){
   int k = 0;
    while(k <= start && k < n - end && s.charAt(start - k) == s.charAt(end + k)){
        count++;
        k++;
    } 
}

}
'''

2. DP

'''
public int countSubstrings(String s) {
int n = s.length();
int res = 0;
boolean[][] dp = new boolean[n][n];
for (int i = n - 1; i >= 0; i--) {
for (int j = i; j < n; j++) {
dp[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 3 || dp[i + 1][j - 1]);
if(dp[i][j]) ++res;
}
}
return res;
}
'''

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,779评论 0 33
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,060评论 0 2
  • 【程序1】 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔...
    叶总韩阅读 5,168评论 0 41
  • 后门的高奶奶馄饨铺,贴心得就像亲奶奶开的。 大大的碗,装满,大大的馄饨,每一个,都鼓鼓的,像是小肚子。 想家,或是...
    俚予阅读 5,257评论 1 1
  • 漆黑的夜遮不住月亮的清辉,冷冷的打在我的脸上。我独自走在这条无人的小路上,内心只有宁静,全然没有以前的惴...
    孤馆深沉阅读 468评论 2 0