一:解题思路
以每个字符串中的字符为中分别向两边进行扩展,然后对比是否相等。比如:aba 有4个回文字符串。abba有6个回文字符串。Time:O(n^2),Space:O(1)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: int expand(string s, int left, int right) { int count = 0; while (left >= 0 && right < s.size() && s[left] == s[right]) { count++; left--; right++; } return count; } int countSubstrings(string s) {
if(s.size()==0) return 0; int count = 0; for (int i = 0; i < s.size(); i++) { count += expand(s,i,i); count += expand(s,i,i+1); } return count; } };
Java:
class Solution { private int expand(String s,int left,int right) { int count=0; while(left>=0 && right<s.length() && s.charAt(left)==s.charAt(right)) { count++; right++; left--; } return count; } public int countSubstrings(String s) { if(s==null || s.length()==0) return 0; int count=0; for(int i=0;i<s.length();i++) { count+=expand(s,i,i); count+=expand(s,i,i+1); } return count; } }