zoukankan      html  css  js  c++  java
  • LeetCode 647. Palindromic Substrings

    原题链接在这里:https://leetcode.com/problems/palindromic-substrings/description/

    题目:

    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:

    1. The input string length won't exceed 1000.

    题解:

    对于String s的每一位向左右延展看是不是palindrome. 延展时有奇数偶数个char的substring两种情况.

    Time Complexity: O(n^2). 延展用时2*(1+2+ ... + n/2 + ... +2+1) = O(n^2).

    Space: O(1).

    AC Java:

     1 class Solution {
     2     int count = 0;
     3     
     4     public int countSubstrings(String s) {
     5         if(s == null || s.length() == 0){
     6             return 1;
     7         }
     8         
     9         for(int i = 0; i<s.length(); i++){
    10             // 有奇数char的substring
    11             extendSubstring(s, i, i); 
    12             // 有偶数char的substring
    13             extendSubstring(s, i, i+1);
    14         }
    15         
    16         return count;
    17     }
    18     
    19     private void extendSubstring(String s, int l, int r){
    20         while(l>=0 && r<s.length() && s.charAt(l)==s.charAt(r)){
    21             count++;
    22             l--;
    23             r++;
    24         }
    25     }
    26 }

    类似Longest Palindromic Substring.

  • 相关阅读:
    使用rem,动态设置root font size
    手机陀螺仪
    获取图片
    插件整理
    jquery图片懒加载
    关于underscore.js
    PCA
    Endnote9
    实验问题记录
    DN/TOA/SR
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7595234.html
Copyright © 2011-2022 走看看