📅  最后修改于: 2023-12-03 15:12:46.526000             🧑  作者: Mango
本题是门|门 IT 2006年的一道编程题目,需要完成以下任务:
find_palindrome
的函数,函数接收一个字符串作为参数,返回该字符串中所有回文子串的个数。以下是函数原型及示例:
def find_palindrome(s: str) -> int:
pass
print(find_palindrome('level')) # 5
print(find_palindrome('1221')) # 5
编写代码:
def find_palindrome(s: str) -> int:
count = 0
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if s[i:j] == s[i:j][::-1]:
count += 1
return count
public static int find_palindrome(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
if (s.substring(i, j).equals(new StringBuilder(s.substring(i, j)).reverse().toString())) {
count++;
}
}
}
return count;
}
int find_palindrome(string s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j <= s.length(); j++) {
string sub = s.substr(i, j - i);
if (equal(sub.begin(), sub.end(), sub.rbegin())) {
count++;
}
}
}
return count;
}
以上是三种不同语言的实现,你可以根据自己喜欢的语言进行选择。如果你想查看更多主题,请浏览门|门 IT网站(https://www.menmen-it.com/)。