Home > Enterprise >  Palindrome in java
Palindrome in java

Time:01-24

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

CodePudding user response:

In your version you compare first element with last, second with second last etc. last element in this case is inputString.length()-1(so need to use 'inputString.charAt(val-i-1)' . If you iterate till end, then the count should be equal to length of the string.

for(int i = 0; i<inputString.length(); i  ){
   if(inputString.charAt(i) == inputString.charAt(val-i-1)){
       count   ;
   }
 }
 return (count==val); //true when count=val

Or alternatlively iterate till the mid point of the array, then count value is val/2.

for(int i = 0; i<inputString.length()/2; i  ){
   if(inputString.charAt(i) == inputString.charAt(val-i-1)){
       count   ;
   }
 }
 return (count==val/2);  //true when count=val/2

CodePudding user response:

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

CodePudding user response:

There's no constraints in the question so let me throw in a more cheesy solution.

boolean isPalindrome(String in) 
    final String inl = in.toLowerCase();
    return new StringBuilder(inl).reverse().toString().equals(inl);
}
  •  Tags:  
  • Related