【发布时间】:2019-06-19 23:21:59
【问题描述】:
我想找出使用给定字符串中的子字符串可能出现的所有可能的回文。
Example: input = abbcbbd.
Possible palindromes are a,b,b,c,b,b,d,bb,bcb, bbcbb,bb
这是我实现的逻辑:
public int palindromeCount(String input) {
int size = input.length();// all single characters in string are treated as palindromes.
int count = size;
for(int i=0; i<size; i++) {
for(int j=i+2; j<=size; j++) {
String value = input.substring(i, j);
String reverse = new StringBuilder(value).reverse().toString();
if(value.equals(reverse)) {
count++;
}
}
}
return count;
}
这里时间复杂度比较高,请问如何提高这个逻辑的性能?
【问题讨论】:
-
all possible palindromes that can be possible from a given string.是什么意思?你的意思是重新排列字母还是严格的子字符串 -
@JClassic,是的,只有严格的子字符串更新了我的问题以使其清楚
-
你的例子中的
bcb怎么样? -
@Code-Apprentice,是的,我错过了,现在包含在其中
-
您确定要像您的示例那样多次显示相同的回文吗?我希望 abbcbbd 产生 a、b、c、d、bb、bab、bbb、bcb、bdb、bbbb、bbabb、bbcbb、bbdbb。
标签: java string algorithm palindrome