一个只包含’A’、’B’和’C’的字符串,如果存在某一段长度为3的连续子串中恰好’A’、’B’和’C’各有一个,那么这个字符串就是纯净的,否则这个字符串就是暗黑的。例如:
BAACAACCBAAA 连续子串”CBA”中包含了’A’,’B’,’C’各一个,所以是纯净的字符串
AABBCCAABB 不存在一个长度为3的连续子串包含’A’,’B’,’C’,所以是暗黑的字符串
你的任务就是计算出长度为n的字符串(只包含’A’、’B’和’C’),有多少个是暗黑的字符串。
输入描述:
输入一个整数n,表示字符串长度(1 ≤ n ≤ 30)
输出描述:
输出一个整数表示有多少个暗黑字符串
输入例子1:
2
3
输出例子1:
9
21
解题思路
将字符串分为两种
- 结尾两个字符是相同的
- 结尾两个字符是不同的
-
那么有如下转移方程,其中i表示前i个字符。
same[i] =same[i-1] +notSame[i-1];
notSame[i]=2*same[i-1] + notSame[i-1];
注意:两个数组要定义为long类型,不然会越界。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n == 1) {
System.out.println(3);
return;
}
if (n == 2) {
System.out.println(9);
return;
}
long[] same = new long[n];
long[] notSame = new long[n];
notSame[1] = 6;
same[1] = 3;
for (int i = 2; i < n; i++) {
same[i] = same[i - 1] + notSame[i - 1];
notSame[i] = 2 * same[i - 1] + notSame[i - 1];
}
System.out.println(same[n - 1] + notSame[n - 1]);
}
}