Search code examples
javastringalgorithmpalindrome

Checking if a string is a palindrome in Java


I'm using a simple function to check if a string is a palindrome. But the program goes into an infinite loop.

public static boolean checkPalindrome(String s){

        boolean check = true;
        int mid = s.length()/2;
        int j = s.length() -1;
        int i = 0;
        if (s.length()%2 == 0) {
            while(i <= mid){
                if (s.charAt(i) != s.charAt(j)){
                    check = false;
                    j--;
                    i++;
                }
            }
        }else if(s.length()%2 != 0){
            while(i < mid +1 ){
                if (s.charAt(i) == s.charAt(j)){
                    check = false;
                    j--;
                    i++;
                }
            }
        }
        return check;

    }

Solution

  • There's no need to be doing difficult loops like that. Something like this will work:

    boolean isPalindrome(String s) {
       for (int i = 0; i < s.length()/2; i++) {
          if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false;
       }
    
       return true;
    }