題目描述:
輸入一個字符串str,輸出str包含的所有迴文串的個數。如ABA,包含的迴文串有A,B,A,AA,ABA共5個。
思路:
長度爲N的str的不打亂原始順序所有可能的字符子串個數爲2^N個,再判定每一個子串是否是迴文串。
感覺可以用動態規劃,但是目前沒有想到如何建模。
代碼如下:
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(numOfPalindrome(str));
}
public static int numOfPalindrome(String str) {
if (str == null || str.length() == 0)
return 0;
int N = str.length(), i = 1, num = 0, j = 0, flag = 1;
StringBuffer sb = null;
while (i < (int) Math.pow(2, N)) {
j = 0;
flag = 1;
sb = new StringBuffer();
while (j < N) {
if ((i & flag) != 0)
sb.append(str.charAt(j));
j++;
flag = flag << 1;
}
if (isPalindrome(sb, 0, sb.length() - 1)) {
System.out.println(sb);
num++;
}
i++;
}
return num;
}
public static boolean isPalindrome(StringBuffer sb, int start, int end) {
while (start <= end && sb.charAt(start) == sb.charAt(end)) {
start++;
end--;
}
return (start > end);
}
}
輸入輸出如下:
aba
a
b
a
aa
aba
5