problem no 74: given is the string consisting of the lower case alphabets find the repeated charachter first in the string.
problem:
Given a string consisting of lowercase english alphabets. Find the repeated character present first in the string.
Example 1:
Input:
S = "geeksforgeeks"
Output: g
Explanation: g, e, k and s are the repeating
characters. Out of these, g occurs first.
​Example 2:
Input:
S = "abcde"
Output: -1
Explanation: No repeating character present.
Your Task:
You don't need to read input or print anything. Your task is to complete the function firstRep() which takes the string S as input and returns the the first repeating character in the string. In case there's no repeating character present, return '#'.
code:
my approach is we will take two maps. map1 and map2. map1 will store the count of each charachter in the string. we will iterate the map1 and see if there is any element inside map1 whose count is greater than 1.if count of any charachter inside map1 is greater than 1 then we will check the first index of that charachter inside the string and we will store charachter and index in map2.
now if map2 size is zero then we will return '#'.because there is no repeating charachter inside the string . if the map2 size is greater than zero then we will iterate over the map2 and store the value of minimum index in the variable min.
now we will iterate over map2 again and check whether there is any index which is equal to min.if yes ,then we will return the charachter whose index is equal to min.
char firstRep (string s)
{
//code here.
map<char,int> map1;
map<char,int> map2;
for(int i=0;i<s.size();i++)
{
map1[s[i]]++;
}
for(auto ele: map1)
{
if(ele.second>1)
{
for(int i=0;i<s.size();i++)
{
if(s[i]==ele.first)
{
map2[ele.first]=i+1;
break;
}
}
}
}
if(map2.size()==0)
{
return '#';
}
int min=INT32_MAX;
for(auto ele:map2)
{
if(ele.second<min)
{
min=ele.second;
}
}
for(auto ele:map2)
{
if(ele.second==min)
{
return ele.first;
}
}
}
Comments
Post a Comment