14. 最长公共前缀
var longestCommonPrefix = function (strs) {
let ans = strs[0];
for (let i = 1; i < strs.length; i++) {
let j = 0;
for (; j < strs[i].length && j < ans.length; j++) {
if (ans[j] !== strs[i][j]) {
break;
}
}
ans = ans.slice(0, j);
if (ans === "") return ans;
}
return ans;
};
longestCommonPrefix(["flower", "flow", "flight"]);
longestCommonPrefix(["dog", "racecar", "car"]);
longestCommonPrefix(["ab", "a"]);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
605.种花问题
var canPlaceFlowers = function (arr, n) {
arr.push(0);
arr.unshift(0);
let count = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] == 0 && arr[i - 1] == 0 && arr[i + 1] === 0) {
count += 1;
arr[i] = 1;
}
}
console.log(count);
return n <= count;
};
canPlaceFlowers([1, 0, 0, 0, 1], 1);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
165. 比较版本号
var compareVersion = function (version1, version2) {
const arr1 = version1.split(".").map(Number);
const arr2 = version2.split(".").map(Number);
while (arr1.length && arr2.length) {
let a1 = arr1.shift();
let a2 = arr2.shift();
if (a1 > a2) return 1;
if (a1 < a2) return -1;
}
if (arr1.length) {
return arr1.every((item) => item === 0) ? 0 : 1;
}
if (arr2.length) {
return arr2.every((item) => item === 0) ? 0 : -1;
}
return 0;
};
console.log(compareVersion("1.01", "1.001"));
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30