Input:
s ="abccbaacz"Output:
"c"Explanation:
The letter 'a' appears on the indexes 0,5 and 6.The letter 'b' appears on the indexes 1 and 4.The letter 'c' appears on the indexes 2,3 and 7.The letter 'z' appears on the index 8.The letter 'c'is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
Example 2:
1
2
3
4
5
6
Input:
s ="abcdd"Output:
"d"Explanation:
The only letter that appears twice is'd' so we return'd'.
We need to find the first letter that appears twice in the string. By iterating through the string and keeping track of seen letters in a hash set, we can immediately return the first letter that is already in the set.
classSolution {
publiccharrepeatedCharacter(String s) {
Set<Character> seen =new HashSet<>();
for (char c : s.toCharArray()) {
if (seen.contains(c)) return c;
seen.add(c);
}
return'a'; // guaranteed to find a repeated character }
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
public:char repeatedCharacter(string s) {
unordered_set<char> seen;
for (char c : s) {
if (seen.count(c)) return c;
seen.insert(c);
}
return'a'; // guaranteed to find a repeated character
}
};
1
2
3
4
5
6
7
classSolution:
defrepeatedCharacter(self, s: str) -> str:
seen = set()
for c in s:
if c in seen:
return c
seen.add(c)