classSolution { publiccharrepeatedCharacter(String s) { Set<Character> seen = newHashSet<Character>(); for (inti=0; i < s.length(); i++) { charch= s.charAt(i); if (!seen.add(ch)) { return ch; } } // impossible return' '; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12
publicclassSolution { publiccharRepeatedCharacter(string s) { ISet<char> seen = new HashSet<char>(); foreach (char ch in s) { if (!seen.Add(ch)) { return ch; } } // impossible return' '; } }
[sol1-Python3]
1 2 3 4 5 6 7
classSolution: defrepeatedCharacter(self, s: str) -> str: seen = set() for ch in s: if ch in seen: return ch seen.add(ch)
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11
charrepeatedCharacter(char * s) { int seen[26]; memset(seen, 0, sizeof(seen)); for (int i = 0; s[i] != '\0'; i++) { if (seen[s[i] - 'a'] > 0) { return s[i]; } seen[s[i] - 'a'] = 1; } return' '; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var repeatedCharacter = function(s) { const seen = newSet(); for (let i = 0; i < s.length; i++) { const ch = s[i]; if (seen.has(ch)) { return ch; } seen.add(ch); } // impossible return' '; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10
funcrepeatedCharacter(s string)byte { seen := map[rune]bool{} for _, c := range s { if seen[c] { returnbyte(c) } seen[c] = true } return0// impossible }
publicclassSolution { publiccharRepeatedCharacter(string s) { int seen = 0; foreach (char ch in s) { int x = ch - 'a'; if ((seen & (1 << x)) != 0) { return ch; } seen |= (1 << x); } // impossible return' '; } }
[sol2-Python3]
1 2 3 4 5 6 7 8
classSolution: defrepeatedCharacter(self, s: str) -> str: seen = 0 for ch in s: x = ord(ch) - ord("a") if seen & (1 << x): return ch seen |= (1 << x)
[sol2-C]
1 2 3 4 5 6 7 8 9 10 11 12
charrepeatedCharacter(char * s) { int seen = 0; for (int i = 0; s[i] != '\0'; i++) { int x = s[i] - 'a'; if (seen & (1 << x)) { return s[i]; } seen |= (1 << x); } // impossible return' '; }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13
var repeatedCharacter = function(s) { let seen = 0; for (let i = 0; i < s.length; i++) { const ch = s[i]; const x = ch.charCodeAt() - 'a'.charCodeAt(); if ((seen & (1 << x)) !== 0) { return ch; } seen |= (1 << x); } // impossible return' '; };
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10
funcrepeatedCharacter(s string)byte { seen := 0 for _, c := range s { if seen>>(c-'a')&1 > 0 { returnbyte(c) } seen |= 1 << (c - 'a') } return0// impossible }