手撕代码系列(三)
手写匹配括号 isValid
const isValid = symbolStr => {
let stack = [];
let obj = {
'(': ')',
'[': ']',
'{': '}',
};
for (let i = 0; i < symbolStr.length; i++) {
let ele = symbolStr[i];
if (Object.prototype.hasOwnProperty.call(obj, ele)) {
stack.push(ele);
} else {
if (ele != obj[stack.pop()]) return false;
}
}
return !stack.length;
};
console.log("isValid('(){}') ------>", isValid('(){'));
手写大驼峰转下划线 camelCasetoLineCase
const camelCasetoLineCase = str => {
return str.replace(/([A-Z])/g, '_$1').toLowerCase();
};
console.log("camelCasetoLineCase('helloWorld') ------>", camelCasetoLineCase('helloWorld'));
var str = 'Doe, John';
let res = str.replace(/(\w+)\s*, \s*(\w+)/, '$2 $1');
console.log('res ------>', res);
手写下划线转大驼峰 lineCasetocamelCase
const lineCasetocamelCase = str => {
return str.replace(/\_(\w)/g, (sourceLetter, letter) => {
console.log('sourceLetter ------>', sourceLetter, letter);
return letter.toUpperCase();
});
};
console.log("linetoHump('hello_world') ------>", linetoHump('hello_world'));
手写反转字符串 reverseStr
const reverseStr = str => {
let strArr = str.split('');
let left = 0;
let right = strArr.length;
while (left <= right) {
[strArr[left], strArr[right]] = [strArr[right], strArr[left]];
left++;
right--;
}
return strArr.join('');
};
console.log("reverseStr('helloworld') ------>", reverseStr('helloworld'));
深度优先遍历 DFS(Depth First Search)
class Node {
constructor(val) {
this.key = val;
this.left = null;
this.right = null;
}
}
let root = null;
let arr = [];
const preOrder = node => {
if (node === null) return;
arr.push(node.key);
preOrder(node.left);
preOrder(node.right);
return arr;
};
const inOrder = node => {
if (node === null) return;
inOrder(node.left);
arr.push(node.key);
inOrder(node.right);
return arr;
};
const postOrder = node => {
if (node === null) return;
postOrder(node.left);
postOrder(node.right);
arr.push(node.key);
return arr;
};
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.right = new Node(6);
root.left.left = new Node(4);
root.left.right = new Node(5);
特殊字符描述:
- 问题标注
Q:(question)
- 答案标注
R:(result)
- 注意事项标准:
A:(attention matters)
- 详情描述标注:
D:(detail info)
- 总结标注:
S:(summary)
- 分析标注:
Ana:(analysis)
- 提示标注:
T:(tips)
打开App,阅读手记