Minimum Length of String After Deleting Similar Ends
Problem Link:
My approach:
Take two pointers 'si=0' and 'ei=n-1'
Create one count = 0 variable to store number of deletion.
Run a while loop and remember they cannot intersect (si < ei)
if str[si] == str[ei]
Count all the characters from 'si' equal to str[si] and update:
- si++, count++
Count all the characters from 'ei' equal to str[si] and update :
- e--, count++
if at any point str[si] != str[ei], break out from the loop.
Return n-count
Code:
// TIME COMPLEXITY : O(N)
// SPACE COMPLEXITY : O(1)
class Solution {
public:
int minimumLength(string s) {
int ind = 0;
int n = s.size();
int si = 0;
int ei = n-1;
while(si<ei){
if(s[si]==s[ei]){
char ch = s[si];
while(si<=ei){
if(s[si]==ch){
si++;
ind++;
}
else{
break;
}
}
while(ei>si){
if(s[ei]==ch){
ei--;
ind++;
}
else{
break;
}
}
}
else{
break;
}
}
return n-ind;
}
};