Leetcode: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:

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

这个题乍一看还挺简单的,代码也一下子嗖嗖就写出来了,而且没有啥特殊值,直接一次AC ,但作为leetcode资深研究者,这个题一看就并不简单(⊜‿⊜✴)

 1 class Solution {
 2     public static boolean isPalindromic(String s)
 3     {
 4         //boolean flag = true;
 5         for(int i = 0,j = s.length() - 1; i < s.length() ; i++,j--)
 6         {
 7             if(s.charAt(i)!=s.charAt(j))
 8                 return false;
 9         }
10         return true;
11     }
12     public int countSubstrings(String s) {
13         if(s.length() == 0)
14             return 0;
15         int num = 0;
16         for(int length = 1 ; length <= s.length() ; length++) //子串的长度
17         {
18             for(int start = 0 ; start < s.length() - length + 1 ; start++)
19             {
20                 String sub = s.substring(start,start + length);
21                 if(isPalindromic(sub))
22                     num++;
23             }
24         }
25         return num;
26     }
27 }

看上面的代码整洁工整,简约漂亮,基本上没有任何一行多余,没有任何一个变量没用但是这个是O(n*n)的显然性能不怎么好

我先吃个饭等会儿回来写

 

 

转载于:https://www.cnblogs.com/jiangnan-0817/p/9636791.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值