LeetCode - Algorithms - 387. First Unique Character in a String

虽然是Easy的题,自己却想不出来,最后只好参考了这个 Given a string, find its first non-repeating character 的思路,倒也很容易看明白,一点就破的题。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public int firstUniqChar(String s) {
Map<Character,Integer> count = new HashMap<Character,Integer>();
char c = '\u0000';
for(int i=0;i<s.length();i++) {
c = s.charAt(i);
if (count.containsKey(c)) {
count.put(c, count.get(c)+1);
}
else {
count.put(c, 1);
}
}

int r = -1;
for(int i=0;i<s.length();i++) {
if (count.get(s.charAt(i))==1) {
r = i;
break;
}
}
return r;
}
}

Submission Detail

  • 104 / 104 test cases passed.
  • Runtime: 61 ms
  • Your runtime beats 25.39 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @param {string} s
* @return {number}
*/
var firstUniqChar = function(s) {
var count = {};
for(var i=0;i<s.length;i++) {
if (typeof count[s[i]]!="undefined" && count[s[i]]!=null) {
count[s[i]]++;
}
else {
count[s[i]]=1;
}
}
var r=-1;
for(var i=0;i<s.length;i++) {
if (count[s[i]]==1) {
r=i;
break;
}
}
return r;
};

Submission Detail

  • 104 / 104 test cases passed.
  • Runtime: 108 ms
  • Your runtime beats 37.23 % of javascript submissions.