File tree Expand file tree Collapse file tree 2 files changed +28
-0
lines changed
algorithms/longestCommonPrefix-jcc Expand file tree Collapse file tree 2 files changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 ">
5
+ < meta http-equiv ="X-UA-Compatible " content ="IE=edge ">
6
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
7
+ < title > Document</ title >
8
+ </ head >
9
+ < body >
10
+
11
+ </ body >
12
+ < script src ="./longestCommonPrefix.js "> </ script >
13
+ </ html >
Original file line number Diff line number Diff line change
1
+ var longestCommonPrefix = function ( strs ) {
2
+ if ( strs . length == 0 ) return "" ;
3
+ let str = strs [ 0 ] ; // 取第一个用来做基准比较
4
+ for ( let i = 1 ; i < strs . length ; i ++ ) { // 不需要跟自己比较,从1开始
5
+ let j = 0 ;
6
+ for ( ; j < str . length && j < strs [ i ] . length ; j ++ ) {
7
+ if ( str [ j ] != strs [ i ] [ j ] ) break ; // 有不想等的就跳出循环
8
+ }
9
+ str = str . substr ( 0 , j ) ; // 截取相等的部分
10
+ if ( str === "" ) return str ;
11
+ }
12
+ return str ;
13
+ } ;
14
+
15
+ console . log ( longestCommonPrefix ( [ "flower" , "flow" , "flight" ] ) ) ;
You can’t perform that action at this time.
0 commit comments