user3283997
user3283997

Reputation:

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;

    }

Upvotes: 1

Views: 5248

Answers (6)

KontrCode
KontrCode

Reputation: 89

You can actually do this only by using for loops and few lists as follows:

public class Palindrome {

    public static void main(String[] args) {

        String str = "racecar";
        isPalindrome(str);

    }

    public static boolean isPalindrome(String str) {

        // if number is odd
        if (str.length() % 2 != 0) {
            List<String> counter = new ArrayList<>();

            for (int i = 0; i <= (str.length() - 1) / 2; i++) {
                for (int j = str.length() - 1; j >= (str.length() - 1) / 2; j--) {
                    if (str.charAt(i) == str.charAt(j)) {
                        counter.add("+");
                    }

                }
            }
            System.out.println(counter.toString());
            if (counter.size() == (str.length() + 1) / 2) {
                System.out.println("String is an odd palindrome");
            } else
                System.out.println("String is not a palindrome");
        }
        // if number is even
        else {
            List<String> counter_even = new ArrayList<>();

            for (int i = 0; i < (str.length()) / 2; i++) {
                for (int j = str.length() - 1; j >= (str.length()) / 2; j--) {
                    if (str.charAt(i) == str.charAt(j)) {
                        counter_even.add("+");
                    }

                }
            }
            System.out.println(counter_even.toString());
            if (counter_even.size() == (str.length()) / 2) {
                System.out.println("String is an even palindrome");
            } else
                System.out.println("String is not a palindrome");
        }
        return false;

    }

}

Here, we basically split our string and compare its first half to the second half. If they are identical to each other, then we increment our list by adding '+' per each identical letter in both halves. If the number of '+'s (which can be replaced by any random letter as long as it helps us to count) in our list is equal to result of (str.length() + 1) / 2 for our odd string, or equal to (str.length()) / 2 for our even string, then we can conclude that our String is a palindrome.

Upvotes: 0

huseyin
huseyin

Reputation: 1427

class CheckPalindrome {
    boolean isPalindrome(String text) {
        int i = 0;
        int j = text.length() - 1;
        while (i < j) {
            while (!Character.isLetter(text.charAt(i)) && i < j) {
                ++i;
            }
            while (!Character.isLetter(text.charAt(j)) && i < j) {
                --j;
            }
            if (Character.toLowerCase(text.charAt(i++)) != Character.toLowerCase(text.charAt(j--))) {
                return false;
            }
        }
        return true;
    }
}




 @Test
    public void isPalindrome() throws Exception {

        CheckPalindrome checkPalindrome = new CheckPalindrome();
        String text = "No, it is opposition";
        assertTrue(checkPalindrome.isPalindrome(text));

    }

Upvotes: 0

user5150135
user5150135

Reputation:

Try the following code:

public class Palindrome {
private static Scanner input;

public static void main(String args[]) {
    System.out.print("Enter a string:");
    input = new Scanner(System.in);
    String str = input.nextLine();

    System.out.println(palindromeLoop(str));
    System.out.println(palindromeCheck(str));
    System.out.println(palindromeRecursion(str));
}

// Using StringBuffer
public static String palindromeCheck(String str) {
    StringBuffer strName = new StringBuffer(str);
    strName.reverse();

    if (strName.toString().equals(str)) {
        return "The String is a Palindrome";
    } else {
        return "Not a Palindrome!!!";
    }
}

// Using For-Loop
public static String palindromeLoop(String str) {
    String original = str;
    String reverse = "";

    for (int i = str.length() - 1; i >= 0; i--) {
        reverse = reverse + original.charAt(i);
    }

    if (original.equals(reverse)) {
        return "The String is a Palindrome";
    } else {
        return "Not a Palindrome!!!";
    }
}

// Using Recursion
public static String palindromeRecursion(String str) {
    if (str.length() <= 1) {
        return "The String is a Palindrome";
    } else if (str.charAt(0) != str.charAt(str.length() - 1)) // Base case
        return "Not a Palindrome!!!";
    else
        return palindromeRecursion(str.substring(1, str.length() - 1));
}

Upvotes: 0

Khaled Elbanna
Khaled Elbanna

Reputation: 66

You need to move the increment of i and decrement of j out of the inner if conditions and it will not go into infinite loop.

Upvotes: 4

David Xu
David Xu

Reputation: 5607

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;
}

Upvotes: -2

Andy Brown
Andy Brown

Reputation: 19171

Why not just do:

String rev = new StringBuilder(s).reverse().toString();
return rev.equals(s);

Alternatively:

int len = s.length();
for (int i = 0; i < len; i++)
    if (s.charAt(i) != s.charAt(len - i - 1)) return false;
return true;

Upvotes: 2

Related Questions