0% found this document useful (0 votes)
29 views

Amrita Java 3.1

Uploaded by

Ujjawal Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Amrita Java 3.1

Uploaded by

Ujjawal Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 3.1
Student Name: Amrita Chattaraj UID:21BCS8440
Branch: CSE Section/Group:CC_643_B
Semester: 6 Date of Performance:08/03/2024
Subject Name: Project Based Learning in Java Subject Code: 21CSH-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, String in java.

3. Script and Output: package exp8;

import java.util.HashMap;
import java.util.Map;

import java.util.Scanner;
public class exp8 {

public static String longestPalindrome(String str) {


if (str == null || str.length() == 0) {
return str;
}
Map<Character, Integer> freq = new HashMap<>();
for (char ch : str.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
StringBuilder leftHalf = new StringBuilder();
for (var entry : freq.entrySet()) {
char ch = entry.getKey(); int count
= entry.getValue(); if (count % 2
== 1) {
if (midChar.isEmpty())
{
midChar = String.valueOf(ch);
}
count--;
}

leftHalf.append(String.valueOf(ch).repeat(count / 2));
}
StringBuilder rightHalf = new StringBuilder(leftHalf).reverse();
return leftHalf.toString() + midChar + rightHalf.toString();
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.println("Enter your String: ");
String str = in.next();
System.out.println("The longest palindrome is " + longestPalindrome(str));
in.close();
}}

Output:

4. Learning Outcomes:
• Learnt the concept of palindrome.
• Learnt the concept of StringBuilder ().
• Learnt the concept of HashMap ().
• Learnt the concept of StringBuilder Manipulation such as Reverse.

You might also like