Posts Find first repeated character (geeksforgeeks - SDE Sheet)
Post
Cancel

Find first repeated character (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given a string S. The task is to find the first repeated character in it. We need to find the character that occurs more than once and whose index of second occurrence is smallest. S contains only lowercase letters.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution
{
    String firstRepChar(String s)
    {

        int[] f = new int[26];

        for(int i=0; i<s.length(); i++){

            char ch = s.charAt(i);

            if(f[ch-'a'] != 0)
                return String.valueOf(ch);

            f[ch-'a']++;

        }

        return "-1";

    }
}
This post is licensed under CC BY 4.0 by the author.