DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment-3.1
Student Name: Anjali UID: 21BCS4100
Branch: BE-CSE Section: CC-635/A
Subject Name: Java Lab Subject Code: 21CSP-319
1. Aim:
Create a palindrome creator application for making a longest possible palindrome
out of given input string.
2. Objective:
• To learn about concept of HashMap in java.
• To learn about concept of String in java.
3. Algorithm:
• First, we need to consider the type of value.
• If it is a number, we need to change it to a string to compare how it reads
backwards and forwards.
• If it is an object, we need to somehow also change it to a string to do a
comparison.
• If it is a string, we can forge ahead.
• Compare a string with its reversed version.
• Iterate using for loop and check to see if character on other side of string.
• Use recursion to check the first and last letters before invoking the function
again with the shortened string.
4. Code:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class PalindromeCreator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
System.out.println("Enter the input string:");
String inputString = scanner.nextLine();
String palindrome = createPalindrome(inputString);
System.out.println("Longest Palindrome: " + palindrome);
scanner.close();
}
private static String createPalindrome(String input) {
// Count the frequency of each character
Map<Character, Integer> charFrequency = new HashMap<>();
for (char ch : input.toCharArray()) {
charFrequency.put(ch, charFrequency.getOrDefault(ch, 0) + 1);
}
StringBuilder leftHalf = new StringBuilder();
StringBuilder rightHalf = new StringBuilder();
char middleChar = '\0';
// Construct the left and right halves of the palindrome
for (Map.Entry<Character, Integer> entry : charFrequency.entrySet()) {
char ch = entry.getKey();
int frequency = entry.getValue();
// If frequency is even, add half occurrences to both left and right halves
if (frequency % 2 == 0) {
int halfFrequency = frequency / 2;
leftHalf.append(String.valueOf(ch).repeat(halfFrequency));
rightHalf.insert(0, String.valueOf(ch).repeat(halfFrequency));
} else {
// If frequency is odd, add one occurrence to the middle and the rest to
both halves
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
middleChar = ch;
int halfFrequency = (frequency - 1) / 2;
leftHalf.append(String.valueOf(ch).repeat(halfFrequency));
rightHalf.insert(0, String.valueOf(ch).repeat(halfFrequency));
}
}
// Combine left half, middle character (if any), and right half
StringBuilder palindrome = new StringBuilder(leftHalf);
if (middleChar != '\0') {
palindrome.append(middleChar);
}
palindrome.append(rightHalf);
return palindrome.toString();
}
}
5. Output
6. Learning outcomes:
• Learnt about concept of HashMap in java.
• Learnt about concept of String in java.