Skip to content

Commit daf4353

Browse files
committed
截取相同的字符串
1 parent 5ea17c6 commit daf4353

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
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>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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"]));

0 commit comments

Comments
 (0)