-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.js
64 lines (48 loc) · 1.27 KB
/
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
// isUnique
const isUnique = (str) => {
if (str.length > 128) return false;
let arr = new Array(128)
for(let i=0;i<str.length;i++){
const count = str.charCodeAt(i);
if(arr[count]){
return false;
}
arr[count] = true;
}
return true;
}
isUnique("fs")
// checkPermutation
// Sol 1 Complexity = O(n log n)
const stringSort = (str) => ([...str].sort((a,b) => a.localeCompare(b)).join())
const checkPermutation = (str1, str2) => {
if(str1.length !== str2.length) return false;
return stringSort(str1) === stringSort(str2)
};
checkPermutation("asdf","asdf")
// Sol 2 Complexity = O(n)
const checkPermutation1 = (str1, str2) => {
if(str1.length !== str2.length) return false;
const arr = new Array(128).fill(0);
// add to frequency table
for (let i = 0; i<str1.length; i++){
arr[str1.charCodeAt(i)]++;
}
console.log(JSON.stringify(arr))
// subtract from frequency table
for(let i =0; i<str2.length;i++){
arr[str2.charCodeAt(i)]--;
console.log(JSON.stringify(arr))
if(arr[str2.charCodeAt(i)]<0){
return false;
}
}
return true;
};
checkPermutation1("aabcda", "aacba")
// Urlify Function
const urlify = (s1) => {
return s1.split(' ').join('%20');
}
let url = 'javascript algorithms'
console.log(urlify(url));