
1. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入:strs = ["flower","flow","flight"]
输出:"fl"
var longestCommonPrefix = function(strs) {
let first = strs[0];
let res = '';
for(i = 0;i < first.length; i++){
let str = first[i];
for(j = 1; j < strs.length; j++){
if(str !== strs[j][i]){
// 使用return 不单单是终止终止循环,还将不再执行后续的代码
// 另外当使用循环时,大多数应该找到何时结束循环作为条件
return res
}
}
res = res + str;
}
return res;
};
2. 有效的括号
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()"
输出:true
var isValid = function(s) {
// 思路就是,s无论怎么长啥样,如果要满足条件就一定有一对{},(),或[]。然后挨个替换就搞定了。
while(s.length){
let temp = s;
s = s.replace('{}','');
s = s.replace('()','');
s = s.replace('[]','');
// 什么时候结束?当替换了一遍过后,依然没变,那就结束
if(temp === s) return false
}
return true
};
3. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:![]()
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
if(list1 === null){
return list2
}
if(list2 === null){
return list1;
}
if(list1.val < list2.val){
list1.next = mergeTwoLists(list1.next,list2);
return list1;
}else{
list2.next = mergeTwoLists(list1,list2.next);
return list2;
}
};