leetcode one question a day 564 Difficult string splicing to find the number of recent palindromes \ special example input extended thinking

Posted by Lamez on Wed, 02 Mar 2022 11:55:10 +0100

📖 Content of this article: Leetcode daily question 564 Difficult string splicing to find the number of recent palindromes \ special example input extended thinking

📑 Article column: leetcode daily question "punch in daily"

📆 Last updated: February 28, 2022 leetcode daily question 6 Z-shaped transformation simple string simulation problem~

⭐ Algorithm warehouse: the way of small payment algorithm—— Alascanfu-algorithm.git.io

🙊 Personal profile: a Junior Program ape who is studying in a two-year college. In line with paying attention to foundation, clock in algorithm and sharing technology, as a blogger who summarizes personal experience, although he may be lazy sometimes, he will stick to it. If you like blog very much, it is suggested to look at the following line ~ (crazy hint QwQ)

🌇 give the thumbs-up 👍 Collection ⭐ Leaving a message. 📝 One key three connection care program ape, start with you and me

🙊 Write in front 🙊

I finished class this morning and took a nap in the afternoon. When I came back to brush the questions, I felt half numb when I saw the difficulties. A cup of tea, a difficult question and sitting all afternoon. The revolution has not yet succeeded, and Xiaofu still needs to work hard.


Given a string n representing an integer, returns the nearest palindrome integer (excluding itself). If there is more than one, return the smaller one.

"Nearest" is defined as the smallest absolute value of the difference between two integers.

Example 1:

input: n = "123"
output: "121"

Example 2:

input: n = "1"
output: "0"
explain: 0 And 2 are the most recent palindromes, but we return the smallest, which is 0.


  • 1 <= n.length <= 18
  • n consists only of numbers
  • n without leading 0
  • n represents an integer in the range of [1, 10 ^ 18 - 1]

📝 thinking 📝

This question examines the knowledge points

  • Idea: Xiaofu usually constructs an example input for this kind of problem, and then finds out the law of special judgment with the help of the output result of lc, and then continues to think and do the problem.
  • Sample input:
    • If the length of the entered value is 1 & & when the value n > 0, the returned result is the value n-1
    • For the number of powers of 10 𞓜 the number of powers of 10 + 1, the returned result is also the value n-1
    • If the input number is the idempotent of the critical current digit ten, the returned value is n + 2 -- for example, 99, 199, 1999
    • Normal example input: it's easy to think of the same idea that the string is halved, but it also needs to be classified for discussion. For the length of n is an odd number, we can make the left string a obtain one more character number, The number symbol on the right needs to omit the idea of reverse splicing of the last number character / if the length of n is an even number, there is no need to consider the above-mentioned direct reverse splicing. But this is just a splicing idea. We must add constraints according to the meaning of the topic. The purpose here is to obtain the palindrome number with the minimum difference. We must imagine that if it is an odd number, we only need to change the number character in the middle and judge the difference with the current value. The even number can be found through example input, which is only related to the two characters and numbers in the middle. Therefore, we can conclude that whether it is odd or even, the middle value or the two values are affected by the character segment a, so we just need to change the last value, and the related operations of - 1, 0 and 1 to obtain the current palindrome string for rolling comparison.

See Hippo's problem solving code here

⭐ code implementation ⭐

String simulation

 * @author:  Alascanfu
 * @date :  Created in 2022/3/2 15:22
 * @description:  Leetcode Daily question - 2022 / 03 / 02 564. Find the number of recent palindromes
 * @modified By:  Alascanfu
class Solution564 {
    public String nearestPalindromic(String n) {
        int lenth = n.length();
        // Special judgment 1: if the length of the entered number is 1, the value of n-1 will be returned directly
        if (lenth == 1) return String.valueOf(Integer.parseInt(n) - 1);
        // Special judgment 2: if the entered value is a power of 10, such as 10, 100, 1000/ 11,101,1001 ...
        // Its return value is a power of 10 - 1
        // Because n here gives 10 ^ 18, use long to operate
        long curNum = Long.parseLong(n);
        long powOfTen = (long) Math.pow(10, lenth - 1);
        if (curNum == powOfTen || curNum == powOfTen + 1) return String.valueOf(powOfTen - 1L);
        // Special judgment 3: if the entered values are 99, 199, 1999
        // The current value + 2 is returned
        // powOfTen * 10L - 1L stands for critical if 77 = > critical 99 | 99 = > critical 99
        if (curNum == powOfTen * 10L - 1L) {
            return String.valueOf(curNum + 2L);
        long diff = Long.MAX_VALUE;
        long res = Long.MAX_VALUE;
        // Let's divide the numbers into left and right numbers a \ b
        // If the current number is odd, it is mostly A. it should be noted that when there are odd numbers, the characters that need to be spliced and reversed need to ignore the last number of segment a
        long a = Long.parseLong(n.substring(0, (lenth + 1) / 2));
        // Use a-1 | a | a+1 to construct the palindrome number, obtain the palindrome string number with the minimum difference from the current value, and use the rolling variables diff and res to record the difference and result respectively
        for (int i : new int[]{-1, 0, 1}) {
            String aa = (a + i) + "";
            // Splice the string accordingly
            String curResStr = new StringBuilder(lenth % 2 == 1 ? aa.substring(0, aa.length() - 1) : aa).reverse().insert(0, aa).toString();
            if (n.equals(curResStr)) continue;
            if (Math.abs(Long.parseLong(curResStr) - curNum) <= diff) {
                diff = Math.abs(Long.parseLong(curResStr) - curNum);
                res = Math.min(res, Long.parseLong(curResStr));
        return res + "";

Operation results

Difficult string splicing and sample input extension

Local test

 * @author:  Alascanfu
 * @date :  Created in 2022/3/2 17:18
 * @description:  LeetCode Daily question - 564 Find recent palindrome string
 * @modified By:  Alascanfu
public class Test564 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string of numbers:");
        String n = sc.nextLine();
        System.out.println("Its most recent palindrome string is:");
        System.out.println(new Solution564().nearestPalindromic(n));

🙊 Write at the end 🙊

2022-3-2 Xiaofu clocked in today~

Beautiful sunrise, beautiful mountains and rivers

Because of your presence

Topics: Algorithm leetcode