Skip to content
thesarfo

Reference

Palindrome and Anagram Checks

Checking whether a string reads the same reversed, and whether two strings are anagrams of each other.

views 0

Palindrome

A palindrome is a string that reads the same backwards and forwards. Reverse the string, and compare it to the original — if they’re equal, it’s a palindrome.

def is_palindrome(str):
return str == str[::-1]
public boolean isPalindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}

Anagrams

Two strings are anagrams if they contain the same characters in a different order. The straightforward check: break each string into a character array, sort both, and compare — if equal, they’re anagrams.

public boolean isAnagram(String str1, String str2) {
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}

A character-frequency count works just as well, without sorting:

def isAnagram(str1, str2):
return Counter(str1) == Counter(str2)