647. Palindromic Substrings
647. Palindromic Substrings class Solution { public int countSubstrings(String s) { int count=0; for(int i=0;i<s.length();i++){ count+=extractPalindrome(s,i,i);//odd length count+=extractPalindrome(s,i,i+1);//even length } return count; } public int extractPalindrome(String s, int left, int right){ int count=0; while(left>=0 && right<s.length()&& (s.charAt(left)==s.charAt(right))){ left--; right++; count++; } return count; } }
Palindromic Substrings http://www.cnblogs.com/grandyang/p/7404777.html This is O(n^2 http://massivealgorithms.blogspot.com/2016/12/count-all-palindrome-sub-strings-in.html class Solution { int count = 0; public int countSubstrings(String s) { if(s == null || s.length() == 0) return 0; for(int i = 0; i < s.length(); i++){ extend(s, i, i); extend(s, i, i + 1); } return count; } private void extend(String s, int left, int right){ while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){ count++; left--; right++; } } } Other code : public int countSubstrings(String s) { int sum = 0; // Loop across different middle points. for (int i = 0; i < s.length(); i++) { // Find all odd length palindrome with i as middle point. sum += findPalindromic(s, i, i); // Find all even length palindrome with i and i+1 as middle point. sum += findPalindromic(s, i, i + 1); } return sum; } // Expend from the current mid point to all of its low and high positions. private int findPalindromic(String s, int left, int right) { int count = 0; // Increase count if the substring is a validate palindrome. while (left >= 0 && right < s.length() && s.charAt(left--) == s.charAt(right++)) count++; return count; }
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".
posted on 2018-08-28 20:08 猪猪🐷 阅读(73) 评论(0) 收藏 举报
浙公网安备 33010602011771号