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:
1 2 3 4
| >Input: "abc" >Output: 3 >Explanation: Three palindromic strings: "a", "b", "c". >
|
Example 2:
1 2 3 4
| >Input: "aaa" >Output: 6 >Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". >
|
平淡无奇的解法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public int countSubString(String str){ int count = 0; int i = 0; while (i++ < str.length()) { count ++; } for(int j = 2; j <= str.length(); j++){ for(int x = 0; x+j<=str.length(); x++) { if(isPalindrome(str.substring(x,x+j))){ count ++; } } } return count; }
public boolean isPalindrome(String subStr) { for (int i = 0; i < subStr.length(); i++){ if(subStr.charAt(i) != subStr.charAt(subStr.length() - 1 - i)){ return false; } } return true; } }
|
吊炸天的解法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int countSubstrings(String s) { int count = 0; boolean[][] isPalindrome = new boolean[s.length()][s.length()]; for(int i = s.length()-1; i >= 0; i--) { for(int j = i; j < s.length(); j++) { if(i == j || (s.charAt(i) == s.charAt(j) && (isPalindrome[i+1][j-1] || j-i == 1))) { isPalindrome[i][j] = true; count++; } } } return count; } }
|
647.Palindromic Substrings
程序员面试题精选100题(71)-回文子字符串的数目 - 算法