给定一个数 x,要用 r,e,d三种字符构造一个字符串,它的回文子串的数量恰好为 x, 要求字符串的长度小于10^5,而 x 的范围是 [1, 10^9]。
import java.util.Scanner;
public class Red {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
StringBuilder res = new StringBuilder();
String[] strings = {"r","e","d"};
int idx = 0;
while(x != 0){
int sum = 0;
int i = 1;
while(sum + i <= x){
sum += i;
i++;
res.append(strings[idx]);
}
x -= sum;
idx = (idx + 1) % 3;
}
System.out.println(res.toString());
}
}
//rr有3个回文子串,rrr有3+2+1=6个回文子串,rrrr有4+3+2+1=10个回文子串。
//连续n个相同的字符,有 n * (n + 1) / 2 个回文子串。
//第一个字符尽可能多的连续,直到长度为k,有k + (k - 1) + ... + 1个回文子串,如果再加(k+1)个就超过题目要求的x。
// 这时候开始连续下一个字符,直到满足x的数量。
// 因为前面字符连续的长度一定比后面的字符连续长度长,所以不会影响后面的字符形成新的回文子串。
// 例如,rrrrrreeeedd。