虾皮笔试
小驼峰格式转换
- 将字符串转换为小写。
- 使用正则表达式将分隔符替换为空格。
- 使用
split 将字符串分割为数组。
- 将数组中的每个单词首字母大写(除了第一个单词),其余字母小写。
- 使用
join 将数组重新拼接成字符串。
function toCamelCase(str) {
return str
.toLowerCase()
.replace(/[-_\s.]+(.)?/g, (match, chr) => (chr ? chr.toUpperCase() : ''))
.replace(/^[A-Z]/, match => match.toLowerCase());
}
const testCases = [
'hello_world',
'hello-world',
'hello world',
'hello.world',
'Hello World',
'HELLO_WORLD',
'helloWorld',
'this_is-a.test string'
];
testCases.forEach(testCase => {
console.log(`${testCase} -> ${toCamelCase(testCase)}`);
});
实现一个无序数组,找到一个数,左边比他大,右边比他小
function findElement(arr) {
const n = arr.length
if (n < 3) return -1
const leftMax = new Array(n).fill(0)
const rightMin = new Array(n).fill(0)
// 填充 leftMax 数组
leftMax[0] = -Infinity
for (let i = 1
leftMax[i] = Math.max(leftMax[i - 1], arr[i - 1])
}
// 填充 rightMin 数组
rightMin[n - 1] = Infinity
for (let i = n - 2
rightMin[i] = Math.min(rightMin[i + 1], arr[i + 1])
}
// 找到满足条件的元素
for (let i = 0
if (arr[i] > leftMax[i] && arr[i] < rightMin[i]) {
return arr[i]
}
}
return -1
}
// 测试用例
const testArray = [5, 1, 4, 3, 6, 8, 2, 7]
const result = findElement(testArray)
console.log(result)