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; }};