DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment 3.1
Student Name: Pranshu Mishra UID: 21BCS9583
Branch: B.E CSE Section/Group: CC_621_A
Semester: 6th Date of Performance: 27/03/24
Subject Name: JAVA Subject Code: 21CSP-314
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. Program Code:
package java_programs;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class experiment_8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
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);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
}
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
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();
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
4. Output:
5. Learning Outcomes:
• Learnt about concept of HashMap in java.
• Learnt about concept of String in java.