JAVA - 3.1 Amar
JAVA - 3.1 Amar
Experiment-3.1
Student Name: Amar Choubey UID: 21BCS11683
Branch: B.E-CSE Section: SC_901 (A)
Subject Name: Java Lab Subject Code: 21CSP-319
Semester: 6th
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;
scanner.close();
}
// 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.