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); } }
The output result is as follows:
沉默王二 对称吗? false 沉默王二 二王默沉 对称吗? true
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!