Skip to content

Commit 5467f4e

Browse files
committed
Longest Common Prefix πŸ’‘
1 parent 5e9dc13 commit 5467f4e

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

β€Žlongest-common-prefix.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {string[]} strs
3+
* @return {string}
4+
*/
5+
const longestCommonPrefix = strs => {
6+
if (!strs || strs.length === 0) {
7+
return '';
8+
}
9+
10+
for (let j = 0; j < strs[0].length; j++) {
11+
for (let i = 1; i < strs.length; i++) {
12+
if (j >= strs[i].length || strs[i][j] !== strs[0][j]) {
13+
return strs[0].substring(0, j);
14+
}
15+
}
16+
}
17+
18+
return strs[0];
19+
};
20+
21+
export { longestCommonPrefix };

0 commit comments

Comments
Β (0)