Check whether a String is a Palindrome

PHOTO EMBED

Tue Feb 08 2022 10:19:51 GMT+0000 (Coordinated Universal Time)

Saved by @Uttam #java #gfg #geeksforgeeks #lecture #string #palindrome

// Efficient : Time Complexity : O(n), Space Complexity : Θ(1)

    static boolean isPalindrome(String str)
    {
 
        // Pointers pointing to the beginning
        // and the end of the string
        int begin = 0, end = str.length() - 1;
 
        // While there are characters to compare
        while (begin < end) {
 
            // If there is a mismatch
            if (str.charAt(begin) != str.charAt(end))
                return false;
 
            // Increment first pointer and
            // decrement the other
            begin++;
            end--;
        }
 
        // Given string is a palindrome
        return true;
    }


// Naive : Time Complexity : Θ(n), Space Complexity : Θ(n)

    static boolean isPalindrome(String str)
    {
      StringBuilder rev = new StringBuilder(str);
      rev.reverse();  // StringBuilder is mutable & has a function called reverse
      
      return str.equals(rev.toString());
    }
content_copyCOPY

Check whether a String is a Palindrome A string is said to be a palindrome if it is the same if we start reading it from left to right or right to left. So let us consider a string “str”, now the task is just to find out with its reverse string is the same as it is. Illustration: Input : str = "abba" Output: Yes Save Input : str = "geeks" Output: No