领扣LintCode算法问题答案-837. 回文子串
837. 回文子串
给定一个字符串,你的任务是数出有多少个回文子串在这个字符串内。
一个子串不同于其他的子串,当且仅当开始和结束位置不同。
输入的字符串长度不会超过1,000
样例 1:
输入: “abc”
输出: 3
解释:
3个回文字符串: “a”, “b”, “c”.
样例 2:
输入: “aba”
输出: 4
解释:
4个回文字符串: “a”, “b”, “a”, “aba”.
题解
public class Solution {
/**
* @param str: s string
* @return: return an integer, denote the number of the palindromic substrings
*/
public int countPalindromicSubstrings(String str) {
// write your code here
int count = 0;
for (int i = 0; i < str.length(); i++) {
int maxIndex = i;
while (maxIndex < str.length()) {
boolean palindromic = true;
for (int j = i; j <= maxIndex; j++) {
if (str.charAt(j) != str.charAt(maxIndex - j + i)) {
palindromic = false;
break;
}
}
if (palindromic) {
count++;
}
maxIndex++;
}
}
return count;
}
}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。