Search code examples
javastringpalindrome

Palindrome in java


Here what I tried sample input is "aabaa"
eg: in if condition val[0] = a[4]
if it is equal i stored it in counter variable if it is half of the length it original string it is palindrome
if it is not it is not a palindrome

I tried with my basic knowledge in java if there is any errors let me know

boolean solution(String inputString) {
  int val = inputString.length();
  int count = 0;
  for (int i = 0; i<inputString.length(); i++) {
    if(inputString.charAt(i) == inputString.charAt(val-i)) {
       count = count++;
      if (count>0) {
        return true;
      }  
    }
  }
  return true;
}

Solution

  • How about

    public boolean isPalindrome(String text) {
        String clean = text.replaceAll("\\s+", "").toLowerCase();
        int length = clean.length();
        int forward = 0;
        int backward = length - 1;
        while (backward > forward) {
            char forwardChar = clean.charAt(forward++);
            char backwardChar = clean.charAt(backward--);
            if (forwardChar != backwardChar)
                return false;
        }
        return true;
    }
    

    From here