Skip to content

Instantly share code, notes, and snippets.

@bonicim
Created December 20, 2022 17:56
Show Gist options
  • Save bonicim/37ff98583ee565caf7732c47b876fc3d to your computer and use it in GitHub Desktop.
Save bonicim/37ff98583ee565caf7732c47b876fc3d to your computer and use it in GitHub Desktop.
Is Palindrome Java
public class Palindrome {
public static void isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
String msgPartial = " is a palindrome";
while (left < right) {
String leftLetter = str.substring(left, left+1);
String rightLetter = str.substring(right, right + 1);
if (leftLetter.equalsIgnoreCase(rightLetter)) {
left++;
right--;
} else {
msgPartial = " is not a palindrome";
left = right;
}
}
System.out.println(str + msgPartial);
}
public static void main(String[] args) {
// tests for palindromes
isPalindrome("t");
isPalindrome("rr");
isPalindrome("rtr");
isPalindrome("tacocat");
// tests for non palindromes
isPalindrome("ab");
isPalindrome("abc");
isPalindrome("rtrx");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment