Topic: Strings
Questions Successfully Completed: 1
1) Repeating Character - First Appearance Leftmost | Easy |
Question
Input: S = geeksforgeeks Output: g Explanation: We see that both e and g repeat as we move from left to right. But the leftmost is g so we print g.
static int repeatedCharacter(String S)
{
/* APPROACH 1
1- Create Hash Table
2- Traverse S and store the count in hash table
3- Traverse S again and check which character value is >1
*/
int[] CharHash = new int[125];
char[] chr = S.toCharArray();
for(int i=0;i<chr.length;i++){
CharHash[chr[i]-'0'+'0']++;
}
for(int j=0;j<chr.length;j++){
if(CharHash[chr[j]-'0'+'0']>1){
return j;
}
}
return -1;
}
Thank you for reading :)