Given an integer array queries and a positive integer intLength, return an array answer where answer[i] is either the queries[i]th smallest positive palindrome of length intLength or -1 if no such palindrome exists.
A palindrome is a number that reads the same backwards and forwards. Palindromes cannot have leading zeros.
Example 1:
Input: queries = [1,2,3,4,5,90], intLength = 3
Output: [101,111,121,131,141,999]
Explanation:
The first few palindromes of length 3 are:
101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, …
The 90th palindrome of length 3 is 999.
Example 2:
Input: queries = [2,4,6], intLength = 4
Output: [1111,1331,1551]
Explanation:
The first six palindromes of length 4 are:
1001, 1111, 1221, 1331, 1441, and 1551.
Constraints:
- 1 <= queries.length <= 5 * 104
- 1 <= queries[i] <= 109
- 1 <= intLength <= 15
这题做着做着突然发现自己不会数数了。。。。。。
这种找回文的,基本都不太可能让你按顺序检查是不是回文, 而是让你去按顺序创造回文。这题其实思考到最后,本质不难,创造回文,其实你只需要创建一半就好,然后镜像一下就是回文了。这个回文是数字, 所以只要保证生成的左边这一半是升序, 那整体一定也是升序。因为不能有前导的0, 所以开始一定是10的n次方这种形式。然后后面的每个数字都可以作为回文的左半边, 剩下的就是根据单双数来确定左半边的长度并且检测查询是不是超出范围了。实现写的不是很好, 还有好多可以简并的部分, 但是太累了, 不改了,能过就行
impl Solution {
fn check(length: i32, n: i64) -> bool {
if length == 1 {
if n > 9 {
return false;
}
return true;
}
Solution::check(length - 1, n / 10)
}
pub fn kth_palindrome(queries: Vec<i32>, int_length: i32) -> Vec<i64> {
let mut ans = Vec::new();
match int_length {
1 => {
for q in queries {
if q > 9 {
ans.push(-1);
continue;
}
ans.push(q as i64);
}
return ans;
}
2 => {
for q in queries {
if q > 9 {
ans.push(-1);
continue;
}
ans.push(q as i64 * 10 + q as i64)
}
}
_ => {
for q in queries {
let half_length = if int_length % 2 == 0 {
int_length / 2
} else {
int_length / 2 + 1
};
if !Solution::check(
half_length,
10i64.pow(half_length as u32 - 1) - 1 + q as i64,
) {
ans.push(-1);
continue;
}
let mut left_half =
(10i64.pow(half_length as u32 - 1) - 1 + q as i64).to_string();
if int_length % 2 == 0 {
left_half.push_str(&left_half.chars().rev().collect::<String>());
} else {
left_half.push_str(&left_half.chars().rev().skip(1).collect::<String>());
}
ans.push(left_half.parse::<i64>().unwrap())
}
}
}
ans
}
}

该博客讨论了一道编程题目,涉及生成指定长度的回文数。博主分享了实现思路,即通过创建数字的一半并镜像得到回文,同时处理边界条件和查询超范围的情况。解决方案中考虑了回文数不能有前导0的限制,并提供了不同长度回文数的生成方法。
2212

被折叠的 条评论
为什么被折叠?



