-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path387.first-unique-character-in-a-string.js
84 lines (78 loc) · 1.87 KB
/
387.first-unique-character-in-a-string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* @lc app=leetcode id=387 lang=javascript
*
* [387] First Unique Character in a String
*
* https://leetcode.com/problems/first-unique-character-in-a-string/description/
*
* algorithms
* Easy (49.67%)
* Total Accepted: 253.3K
* Total Submissions: 509.6K
* Testcase Example: '"leetcode"'
*
*
* Given a string, find the first non-repeating character in it and return it's
* index. If it doesn't exist, return -1.
*
* Examples:
* //l is first non-repeat
* s = "leetcode"
* return 0.
* //v is first non-repeat
* s = "loveleetcode",
* return 2.
* must traverse hole word
*
*
*
* Note: You may assume the string contain only lowercase letters.
*
*/
/**
* @param {string} s
* @return {number}
*/
/*
Sol 1:(not greedy enough)
{
character:firstIndex
}
, if it is already existed when adding, remove the character,
if final has empty map, return -1,
else return the smallest index
Sol 2:
for each character, find the last index from reverse, if it is searched, remove it
var firstUniqChar = function (s) {
//O(N^2)
let repeatingCharacterByCharacter = {};
for (let i = 0; i < s.length; i++) {
let character = s[i];
if (
!repeatingCharacterByCharacter[character] &&
s.indexOf(character) == s.lastIndexOf(character)
) {
return i;
} else {
repeatingCharacterByCharacter[character] = true;
}
}
return -1;
};
*/
//More stable, O(2n)=>O(n)
var firstUniqChar = function (s) {
let occurenceByCharKey = new Array(26).fill(0);
for (let i = 0; i < s.length; i++) {
occurenceByCharKey[s.charAt(i).charCodeAt(0) - "a".charCodeAt(0)]++;
}
// console.log({ occurenceByCharKey });
for (let i = 0; i < s.length; i++) {
let theChar = s.charAt(i);
// console.log({ s, i, theChar });
if (occurenceByCharKey[theChar.charCodeAt(0) - "a".charCodeAt(0)] == 1) {
return i;
}
}
return -1;
};