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.
这个题乍一看还挺简单的,代码也一下子嗖嗖就写出来了,而且没有啥特殊值,直接一次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)的显然性能不怎么好
我先吃个饭等会儿回来写