30 天刷题计划(三)
思路
双指针前后扫描
代码
const isVowel = (ch) => {
return "aeiouAEIOU".includes(ch)
}
const swap = (arr, i, j) => {
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function reverseVowels(s: string): string {
const arr = Array.from(s)
const len = arr.length
let start = 0
let end = len - 1
while(start < end) {
while(start < len && !isVowel(arr[start])) {
start++
}
while(end > 0 && !isVowel(arr[end])) {
end--
}
if (start < end) {
swap(arr, start, end)
start++
end--
}
}
return arr.join("")
};
代码
function reverseWords(s: string): string {
return s.trim().split(/\s+/).reverse().join(' ');
};
思路
代码
function productExceptSelf(nums: number[]): number[] {
const len = nums.length
const l = new Array(len)
const r = new Array(len)
const ans = new Array(len)
l[0] = 1
for(let i = 1; i < len; i++) {
l[i] = nums[i - 1] * l[i - 1]
}
r[len - 1] = 1
for(let i = len - 2; i >= 0; i--) {
r[i] = nums[i + 1] * r[i + 1]
}
for(let i = 0; i < len; i++) {
ans[i] = l[i] * r[i]
}
return ans
};
代码
type ToBeOrNotToBe = {
toBe: (val: any) => boolean;
notToBe: (val: any) => boolean;
};
function expect(val: any): ToBeOrNotToBe {
const toBe = (v) => {
if(val !== v) {
throw Error("Not Equal")
}
return true
}
const notToBe = (v) => {
if (val === v) {
throw Error("Equal")
}
return true
}
return {
toBe,
notToBe
}
};
/**
* expect(5).toBe(5); // true
* expect(5).notToBe(5); // throws "Equal"
*/
转载自:https://juejin.cn/post/7284196027148681256