classSolution { public: intcountSubstrings(string s){ constint n = s.size(); int res = n; // 每個 char 自己本身(對角線)為回文 vector<vector<bool>> dp(n, vector<bool>(n, true));
for (int j = 1; j < n; ++j) { for (int i = 0; i < j; ++i) { dp[i][j] = (s[i] == s[j]) && dp[i + 1][j - 1];
if (dp[i][j]) { ++res; } } } return res; } };
time:$O(n^2)$ ➔ for loop
space:$O(n^2)$ ➔ dp
Solution 2:
想法:利用中心擴散法
classSolution { public: intcountSubstrings(string s){ int res = 0; constint n = s.size(); for (int i = 0; i < n; ++i) { expand(s, i, i, n, res); // odd string expand(s, i, i + 1, n, res); // even string } return res; }
private: voidexpand(const string& s, int left, int right, constint n, int& res){ while (left >= 0 && right < n && s[left] == s[right]) { --left; ++right; ++res; } } };