File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string[] } strs
3
+ * @return {string }
4
+ */
5
+ var longestCommonPrefix = function ( strs ) {
6
+ let results = strs . shift ( ) ;
7
+
8
+ while ( strs . length && results . length ) {
9
+ let key = strs . shift ( ) ;
10
+ if ( key . length < results . length ) {
11
+ results = results . substring ( 0 , key . length ) ;
12
+ } else {
13
+ key = key . substring ( 0 , results . length )
14
+ }
15
+
16
+ while ( results !== key && key . length ) {
17
+ key = key . substring ( 0 , key . length - 1 )
18
+ results = results . substring ( 0 , key . length ) ;
19
+ }
20
+ }
21
+
22
+ return results || "" ;
23
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string[] } strs
3
+ * @return {string }
4
+ */
5
+ var longestCommonPrefix = function ( strs ) {
6
+ if ( strs . length === 0 ) return ""
7
+ let key = strs . shift ( ) . split ( "" )
8
+
9
+ let results = strs . reduce ( ( acc , i ) => {
10
+ let chars = i . split ( "" )
11
+
12
+ if ( key . length > chars . length ) {
13
+ chars . length = key . length
14
+ }
15
+ for ( x = 0 ; x < chars . length ; x ++ ) {
16
+ if ( chars [ x ] !== key [ x ] ) {
17
+ acc . length = x
18
+ break
19
+ }
20
+ }
21
+ return acc
22
+ } , key )
23
+
24
+ return results . join ( "" )
25
+ } ;
You can’t perform that action at this time.
0 commit comments