You are on page 1of 3

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 1.4
Student Name: Sushant Kumar UID: 22BCS90002
Branch: CSE Section/Group: CC_635-A
Semester: 6th Date of Performance: 20/02/2024
Subject Name: AP LAB - 2 Subject Code: 21CSP-351

1. AIM: To demonstrate the concept of Hashing.


2. OBJECTIVE:
Question 1: You are given a string s. You can convert s to a Palindrome by
adding characters in front of it.
Return the shortest palindrome you can find by performing this
transformation.
Question 2: Given a string s, find the length of the longest substring
without repeating characters.
3. SCRIPT & OUTPUT:
Solution 1:
class Solution {
public:
void computelps(vector<int>&lps,string s,int m)
{
int len=0,i=1;
while(i<m)
{
if(s[len]==s[i])
{
len++;
lps[i]=len;
i++;
}
else
{
if(len!=0) len=lps[len-1];
else
{
lps[i]=0;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

i++;
}
}
}
}
string shortestPalindrome(string s) {
int n=s.size();
string ans=s;
s+='#';
for(int i=n-1;i>=0;i--)
{
s+=s[i];
}
vector<int>lps(2*n+2,0);
computelps(lps,s,n+n+1);
string temp="";
for(int i=n-1;i>=lps[2*n];i--)
{
temp+=s[i];
}
return temp+ans;
}
};
Output:
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Solution 2:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.length();
int maxLength = 0;
vector<int> charIndex(128, -1);
int left = 0;
for (int right = 0; right < n; right++) {
if (charIndex[s[right]] >= left) {
left = charIndex[s[right]] + 1;
}
charIndex[s[right]] = right;
maxLength = max(maxLength, right - left + 1);
}
return maxLength;
}
};
Output:

4. LEARNING OUTCOME:
• Learned about how to use KMP approach in DSA problems.
• To implement a basic Hashing program to find shortest Palindrome.
• Apply problem-solving skills to optimize code for both time and space
complexity.

You might also like