Skip to content

Commit 25fa2e3

Browse files
committed
[leet] string, trie (easy)
1 parent 8769dc0 commit 25fa2e3

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var lengthOfLastWord = function(s) {
6+
let stack = [];
7+
const newS = s.trim()
8+
for(let i = 0; i <newS.length; i++ ){
9+
const val = newS[i]
10+
if(val === ' '){
11+
stack = []
12+
}else{
13+
stack.push(val)
14+
}
15+
}
16+
return stack.length
17+
18+
};
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function(strs) {
6+
let prefix = strs[0]
7+
for(let i = 1; i < strs.length ; i++){
8+
while(strs[i].indexOf(prefix) !== 0){
9+
prefix = prefix.substring(0, prefix.length-1)
10+
}
11+
}
12+
return prefix
13+
};
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
var longestCommonPrefix = function (strs) {
6+
if (!strs || strs.length === 0) return "";
7+
if (strs.length === 1) return strs[0];
8+
9+
class TrieNode {
10+
constructor() {
11+
this.children = new Map();
12+
this.isEnd = false;
13+
this.passCount = 0;
14+
}
15+
}
16+
17+
const root = new TrieNode();
18+
19+
for (const word of strs) {
20+
let node = root;
21+
for (const ch of word) {
22+
if (!node.children.has(ch)) {
23+
node.children.set(ch, new TrieNode());
24+
}
25+
node = node.children.get(ch);
26+
node.passCount += 1;
27+
}
28+
node.isEnd = true;
29+
}
30+
31+
let node = root;
32+
let prefix = "";
33+
34+
while (node.children.size === 1) {
35+
const [[ch, next]] = node.children.entries();
36+
37+
if (next.passCount !== strs.length) break;
38+
39+
prefix += ch;
40+
node = next;
41+
if (node.isEnd) break;
42+
}
43+
44+
return prefix;
45+
};

0 commit comments

Comments
 (0)