Skip to content

Instantly share code, notes, and snippets.

@rahogata
Last active July 20, 2023 19:12
Show Gist options
  • Save rahogata/f0a32e9832a47e64b10b5086d3b4f7cd to your computer and use it in GitHub Desktop.
Save rahogata/f0a32e9832a47e64b10b5086d3b4f7cd to your computer and use it in GitHub Desktop.
Palindrome problem solution using checksum for large string.
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
public class PalindromeCheck {
public static void main(String[] args) {
try(Scanner sc=new Scanner(System.in)) {
String A=sc.next();
if (A.length() == 0) {
System.out.println("No");
} else if (A.length() == 1) {
System.out.println("Yes");
} else {
MessageDigest md = MessageDigest.getInstance("MD5");
ArrayDeque<Character> charStack = new ArrayDeque<>(); // Replace with memory efficient stack.
A.chars().mapToObj(e -> (char)e)
.forEach(e -> {
md.update(e.toString().getBytes(StandardCharsets.UTF_8));
charStack.offerFirst(e);
});
byte[] startToEndCrc = md.digest();
md.reset();
for(Character c: charStack) {
md.update(c.toString().getBytes(StandardCharsets.UTF_8));
}
byte[] endToStartCrc = md.digest();
if (MessageDigest.isEqual(startToEndCrc, endToStartCrc)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
} catch(NoSuchAlgorithmException e) {
System.out.println("No");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment