虾皮笔试

140 阅读1分钟

虾皮笔试

小驼峰格式转换

  1. 将字符串转换为小写。
  2. 使用正则表达式将分隔符替换为空格。
  3. 使用 split 将字符串分割为数组。
  4. 将数组中的每个单词首字母大写(除了第一个单词),其余字母小写。
  5. 使用 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; i < n; i++) {
    leftMax[i] = Math.max(leftMax[i - 1], arr[i - 1]);
  }
​
  // 填充 rightMin 数组
  rightMin[n - 1] = Infinity; // 对于最后一个元素,没有右边的元素,所以设为无穷大
  for (let i = n - 2; i >= 0; i--) {
    rightMin[i] = Math.min(rightMin[i + 1], arr[i + 1]);
  }
​
  // 找到满足条件的元素
  for (let i = 0; i < n; i++) {
    if (arr[i] > leftMax[i] && arr[i] < rightMin[i]) {
      return arr[i];
    }
  }
​
  return -1; // 如果没有找到返回 -1
}
​
// 测试用例
const testArray = [5, 1, 4, 3, 6, 8, 2, 7];
const result = findElement(testArray);
console.log(result); // 输出满足条件的元素