Home >Java >javaTutorial >How to Efficiently Determine if a String is a Palindrome?
How to Effectively Check Strings for Palindromes
Checking strings for palindromes involves verifying whether they read identically in both directions. A straightforward approach to this task is to convert the string into a character array and compare adjacent elements.
Here's a sample implementation of this approach:
public class Aufg1 { // Main method for testing public static void main(String[] args) { String wort = "reliefpfpfeiller"; char[] warray = wort.toCharArray(); System.out.println(istPalindrom(warray)); } // Method for checking palindromes public static boolean istPalindrom(char[] word) { boolean palindrom = false; if (word.length % 2 == 0) { for (int i = 0; i < word.length / 2 - 1; i++) { if (word[i] != word[word.length - i - 1]) { return false; } else { palindrom = true; } } } else { for (int i = 0; i < (word.length - 1) / 2 - 1; i++) { if (word[i] != word[word.length - i - 1]) { return false; } else { palindrom = true; } } } return palindrom; } }
This code iterates over the character array, comparing elements at opposite ends to determine if they match. However, a more optimized approach exists that involves comparing elements starting from the beginning and end simultaneously.
Improved Code:
public static boolean istPalindrom(char[] word) { int i1 = 0; int i2 = word.length - 1; while (i2 > i1) { if (word[i1] != word[i2]) { return false; } ++i1; --i2; } return true; }
Example:
Using the input string "andna" as an example:
The above is the detailed content of How to Efficiently Determine if a String is a Palindrome?. For more information, please follow other related articles on the PHP Chinese website!