funcfindTheDifference(s, t string)byte { cnt := [26]int{} for _, ch := range s { cnt[ch-'a']++ } for i := 0; ; i++ { ch := t[i] cnt[ch-'a']-- if cnt[ch-'a'] < 0 { return ch } } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13
var findTheDifference = function(s, t) { const cnt = newArray(26).fill(0); for (const ch of s) { cnt[ch.charCodeAt() - 'a'.charCodeAt()]++; } for (const ch of t) { cnt[ch.charCodeAt() - 'a'.charCodeAt()]--; if (cnt[ch.charCodeAt() - 'a'.charCodeAt()] < 0) { return ch; } } return' '; };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
charfindTheDifference(char* s, char* t) { int cnt[26]; memset(cnt, 0, sizeof(cnt)); int n = strlen(s), m = strlen(t); for (int i = 0; i < n; i++) { cnt[s[i] - 'a']++; } for (int i = 0; i < m; i++) { cnt[t[i] - 'a']--; if (cnt[t[i] - 'a'] < 0) { return t[i]; } } return' '; }
classSolution { public: charfindTheDifference(string s, string t){ int as = 0, at = 0; for (char ch: s) { as += ch; } for (char ch: t) { at += ch; } return at - as; } };
[sol2-Java]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publiccharfindTheDifference(String s, String t) { intas=0, at = 0; for (inti=0; i < s.length(); ++i) { as += s.charAt(i); } for (inti=0; i < t.length(); ++i) { at += t.charAt(i); } return (char) (at - as); } }
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10
funcfindTheDifference(s, t string)byte { sum := 0 for _, ch := range s { sum -= int(ch) } for _, ch := range t { sum += int(ch) } returnbyte(sum) }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10
var findTheDifference = function(s, t) { letas = 0, at = 0; for (let i = 0; i < s.length; i++) { as += s[i].charCodeAt(); } for (let i = 0; i < t.length; i++) { at += t[i].charCodeAt(); } returnString.fromCharCode(at - as); };
[sol2-C]
1 2 3 4 5 6 7 8 9 10 11
charfindTheDifference(char* s, char* t) { int n = strlen(s), m = strlen(t); int as = 0, at = 0; for (int i = 0; i < n; i++) { as += s[i]; } for (int i = 0; i < m; i++) { at += t[i]; } return at - as; }
classSolution { public: charfindTheDifference(string s, string t){ int ret = 0; for (char ch: s) { ret ^= ch; } for (char ch: t) { ret ^= ch; } return ret; } };
[sol3-Java]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publiccharfindTheDifference(String s, String t) { intret=0; for (inti=0; i < s.length(); ++i) { ret ^= s.charAt(i); } for (inti=0; i < t.length(); ++i) { ret ^= t.charAt(i); } return (char) ret; } }
[sol3-Golang]
1 2 3 4 5 6
funcfindTheDifference(s, t string) (diff byte) { for i := range s { diff ^= s[i] ^ t[i] } return diff ^ t[len(t)-1] }
[sol3-JavaScript]
1 2 3 4 5 6 7 8 9 10
var findTheDifference = function(s, t) { let ret = 0; for (const ch of s) { ret ^= ch.charCodeAt(); } for (const ch of t) { ret ^= ch.charCodeAt(); } returnString.fromCharCode(ret); };
[sol3-C]
1 2 3 4 5 6 7 8 9 10 11
charfindTheDifference(char* s, char* t) { int n = strlen(s), m = strlen(t); int ret = 0; for (int i = 0; i < n; i++) { ret ^= s[i]; } for (int i = 0; i < m; i++) { ret ^= t[i]; } return ret; }