-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path387-FirstUniqueCharacterinaString.js
More file actions
68 lines (48 loc) · 1.32 KB
/
387-FirstUniqueCharacterinaString.js
File metadata and controls
68 lines (48 loc) · 1.32 KB
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
//12/07/2020
//given a string, find the first non repeating character and return the index
function first(str){
let obj = {}
for(let i = 0; i < str.length; i++){
if(!obj.hasOwnProperty(str[i])) {
obj[str[i]] = 1
}else{
obj[str[i]] = obj[str[i]] +1
}
}
for(let i = 0; i < str.length; i++){
if(obj[str[i]] ===1){
return i
}
}
}
// time: O(n)
// space: O(1) //bc the alphabet contains only 26 letters.
//first("leetcode") //0
first("loveleetcode")//2
//11/14/2020 Sat w Vicky
//https://leetcode.com/problems/first-unique-character-in-a-string/
// Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
function findNonRepeat(str){
let obj ={}
for(let i = 0; i <str.length; i++){
if(!obj[str[i]]){
obj[str[i]] = 1
} else{
obj[str[i]] = obj[str[i]] +1
}
}
for(let key in obj){
return obj[key] === 1 ? str.indexOf(key): -1 //ternary
}
// if(obj[key] === 1){
// return str.indexOf(key)
// }
// }
// return -1
}
//O(n) time
//O(n) space
//findNonRepeat("leetcode") //0
//findNonRepeat("loveleetcode")//2
//findNonRepeat("love") //0
findNonRepeat("ll") //-1