Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>A non-recursive method that runs under or at O(n/2) in the worst-case (full search). This is more performant when the String is a LONG one... Here's the implementation...</p> <pre><code>class PalindromeClass { /** * This method will run under or at O(n/2) with n = sentence.size() * @param sentence is a given String sentence. * @return true if the given sentence is a palindrome. */ public static boolean isPalindrome(String sentence) { sentence = sentence.replaceAll("[^a-zA-Z0-9]","").toLowerCase(); char[] sentenceChars = sentence.toCharArray(); for (int i = 0; i &lt; sentenceChars.length / 2; i++) { if (sentenceChars[i] != sentenceChars[sentenceChars.length - 1 - i]) { return false; } } return true; } </code></pre> <p>Running this with short, long and with wrong parameters give you the correct values...</p> <pre><code>public static void main(String[] args) { String wrong = "ABCA"; System.out.println("Is '" + wrong + "' a palindrome? "); System.out.println(isPalindrome(wrong)); String none = "A'"; System.out.println("Is '" + none + "' a palindrome? "); System.out.print(isPalindrome(none)); String a = "Madam, I'm Adam"; System.out.println("Is '" + a + "' a palindrome? "); System.out.println(isPalindrome(a)); String b = "abba"; System.out.println("Is '" + b + "' a palindrome? "); System.out.println(isPalindrome(b)); String toyota = "A Toyota. Race fast, safe car. A Toyota."; System.out.println("Is '" + toyota + "' a palindrome? "); System.out.println(isPalindrome(toyota)); String longestPalindrome = "Do good? I? No! Evil anon I deliver. I maim " + "nine more hero-men in Saginaw, sanitary sword a-tuck, Carol, I -- lo! " + "-- rack, cut a drowsy rat in Aswan. I gas nine more hero-men in Miami. " + "Reviled, I (Nona) live on. I do, O God!"; System.out.println("Is '" + longestPalindrome + "' a palindrome? "); System.out.println(isPalindrome(longestPalindrome)); } </code></pre> <p>}</p> <p>Here's the output of the execution...</p> <pre><code>Is 'ABCA' a palindrome? false Is 'a' a palindrome? true Is 'Madam, I'm Adam a palindrome?' true Is 'abba a palindrome? true' Is 'A Toyota. Race fast, safe car. A Toyota.' a palindrome? true Is 'Do good? I? No! Evil anon I deliver. I maim nine more hero-men in Saginaw, sanitary sword a-tuck, Carol, I -- lo! -- rack, cut a drowsy rat in Aswan. I gas nine more hero-men in Miami. Reviled, I (Nona) live on. I do, O God!' a palindrome? true </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload