java palindrome string

Java palindrome

When judging whether a string is a palindrome in Java, there are some things to pay attention to. Here are some common problems and solutions:

1. A palindrome string refers to a string that reads the same from left to right and from right to left. When judging, you need to pay attention to capitalization, that is, to judge whether "A" and "a" are equal. You can use equalsIgnoreCase()the method to compare.

2. To judge a palindrome string, two pointers can be used to move from both ends of the string to the middle, and compare whether each character is equal in turn. String.charAt()Each character can be obtained using the method. When comparing, you need to pay attention to the case where the length of the string is odd and even.

3. In actual use, if you need to determine whether a string is a palindrome, you can also use the method StringBuilderof the class reverse()to reverse the string, and then compare whether the reversed string is equal to the original string. However, it should be noted that using StringBuilderthe class to generate a new string consumes more memory, so this method may not be applicable when the memory is not abundant.

In short, when judging whether a string is a palindrome, we should be able to choose different methods according to our needs. The key is to ensure that the method is correct, efficient and readable.

Example: There is such a kind of character string, they are the same number when looking forward and backward, for example: 121, 656, 2332, ABCBA, etc., such a character string is called a palindrome. Write a Java program to determine whether the string received from the keyboard is a palindrome.

import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("请输入一个字符串:");
        String str = input.nextLine();
        if (isPalindrome(str)) {
    
    
            System.out.println(str + " 是回文串");
        } else {
    
    
            System.out.println(str + " 不是回文串");
        }
    }

    // 判断一个字符串是否为回文串
    public static boolean isPalindrome(String str) {
    
    
        int len = str.length();
        for (int i = 0; i < len / 2; i++) {
    
    
            if (str.charAt(i) != str.charAt(len - 1 - i)) {
    
    
                return false;
            }
        }
        return true;
    }
}

insert image description here

Guess you like

Origin blog.csdn.net/YouWan797411/article/details/130852639