比较失落吧,算法确实需要保持日常,这样才有感觉,今晚两题leetcode easy的题都没做好,第一题没审好题,导致用了太多时间,第二题都没做好,记录一下这两题吧。
Longest String Prefix
var longestPrefix = function(s) {
let maxLength = 0;
if (!s || s.length === 0) {
return maxLength;
}
for (let i = 0; i < s.length - 1; i++) {
if (s.charCodeAt(i) <= s.charCodeAt(i + 1)) {
maxLength += 1;
} else {
break;
}
}
return maxLength > 0 ? maxLength + 1 : maxLength;
};
Swap Nodes
var swapNodes = function(head, k) {
let leftCursor,
rightCursor,
cursor = head,
count = 1,
queue = [];
while (cursor) {
queue.unshift(cursor);
let length = queue.length;
if (length === k) {
leftCursor = queue[length - 1];
}
cursor = cursor.next;
}
rightCursor = queue[k];
// 真实需要交换的节点
let r = rightCursor.next,
l = leftCursor.next,
temp = r.next;
r.next = l.next;
leftCursor.next = r;
rightCursor.next = l;
l.next = temp;
return head;
};