Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does Java determine whether a string is a palindrome string?

Shulou Source: shulou.com Published: 2022-06-02 08:02:55 10月03日 Update

This article mainly explains "Java how to determine whether a string is a palindrome string", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "Java how to judge whether a string is a palindrome string"!

There are two ways to solve the above problems:

(1) Sweep from both ends of the string to the middle;

(2) Sweep from the middle of the string to both ends.

The specific codes are as follows:

import java.util.Scanner;public class StringPalindrome { //Method 1: Sweep both ends to the middle public boolean IsPalindrome1(String A){ char[] arrayA = A.toCharArray(); int top = 0; int end = arrayA.length-1; if(A.equals("") || A.equals(null)) //illegal input return false; while(top

< end){ if(arrayA[top++] != arrayA[end--]) return false; } return true; } //方法2:中间往两头扫 public boolean IsPalindrome2(String A){ char[] arrayA = A.toCharArray(); int lenA = arrayA.length; int mid = lenA/2; int front; //前半部分 int back; //后半部分 if(lenA % 2 == 0){ //当字符串长度为偶数时 front = mid-1; back = mid; } else{ front = mid -1; back = mid + 1; } if(A.equals("") || A.equals(null)) return false; while(front >

= 0 && back < lenA){ if(arrayA[front--] != arrayA[back++]) return false; } return true; } public static void main(String[] args){ StringPalindrome test = new StringPalindrome(); Scanner in = new Scanner(System.in); System.out.println("Please enter a string: "); String A = in.nextLine(); if(test.IsPalindrome1(A)) System.out.println("The result of using method 1 is that the input string is a palindrome string"); else System.out.println("The result of using method 1 is that the input string is not a palindrome string"); if(test.IsPalindrome2(A)) System.out.println("The input string is a palindrome string"); else System.out.println("The result of using method 2 is that the input string is not a palindrome string"); }}

Results:

Please enter a string: I love you. I love you. abba use method 1 to determine the result is, the input string is a palindrome string use method 2 to determine the result is, the input string is a palindrome string to this, I believe we have a deeper understanding of "Java how to determine whether the string is a palindrome string", may wish to actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: Characters strings input palindromes methods results usage both ends content I love learning practical deeper code interest practicality practical I love you easy to operate more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology Xiaomi Redmi OPPO Reno