Home > Java > javaTutorial > body text

How to determine whether a string is symmetrical.

PHPz
Release: 2023-05-09 09:04:07
forward
1560 people have browsed it

How to judge whether a string is symmetrical?

What does it mean? It's like a string that is symmetrical if it is folded back and forth. It's like you stand in front of the mirror and see yourself as a beautiful tree facing the wind, with a moonlight and shy flowers.

public class PalindromeString {     public static void main(String[] args) {          checkPalindromeString("沉默王二");         checkPalindromeString("沉默王二 二王默沉");     }      private static void checkPalindromeString(String input) {         boolean result = true;         int length = input.length();         for (int i = 0; i < length / 2; i++) {             if (input.charAt(i) != input.charAt(length - i - 1)) {                 result = false;                 break;             }         }         System.out.println(input + " 对称吗? " + result);      } }
Copy after login

The output result is as follows:

沉默王二 对称吗? false 沉默王二 二王默沉 对称吗? true
Copy after login

Let me talk about my idea: To determine whether the string is symmetrical after being folded in half, it is very simple, split it from the middle, and compare the first character with the last one Characters, once the one that is not equal is found, return false.

Note three points:

1) The subscript of the for loop starts from 0 and ends at length/2.

2) Subscript i and length-i-1 are symmetrical.

3) Once false, break.

The above is the detailed content of How to determine whether a string is symmetrical.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!