无重复字符的最长子串、乘积小于 K 的子数组、设计链表

54 阅读1分钟

无重复字符的最长子串的示例代码

function longestSubstring(str: string): number {  
  const maxLength = str.length;  
  let start = 0;  
  let end = 0;  
  
  for (let i = 0; i < maxLength; i++) {  
    let char = str[i];  
    while (i < maxLength && str[i] === char) {  
      i++;  
    }  
    end = Math.max(end, i - start + 1);  
  }  
  
  return end;  
}  
  
// 示例用法  
const str = "abcabcbb";  
console.log(longestSubstring(str)); // 输出 9,因为子串为 "abc"

longestSubstring 函数接受一个字符串作为参数,并返回该字符串中无重复字符的最长子串的长度。使用了两个指针 start 和 end 来跟踪子串的起始和结束位置。它使用一个 for 循环来遍历字符串, while 循环来检查当前字符是否为重复字符。如果不是,则将 end 指针向前移动一个位置。

乘积小于 K 的子数组

思路是使用二分查找来查找乘积小于K的子数组。我们首先初始化左右指针,然后在每一次循环中计算左右指针所指向的元素的乘积,如果乘积小于K,则跳出循环,最后,返回左右指针所指向的子数组。

def subarrayProductLessThanK(nums: number[], k: number):  
    left, right = 0, 0  
    leftProduct, rightProduct = 0, 0  
    result = []  
  
    while right < len(nums) and rightProduct * nums[right] < k:  
        leftProduct += nums[right]  
        rightProduct += nums[right+1]  
        if rightProduct * nums[right] < k:  
            break  
        left = (left + 1) % len(nums)  
        right = (right + 1) % len(nums)  
      
    if left >= 0:  
        result.append(left)  
    else:  
        result.append(right)  
  
    return result

设计链表

定义了一个名为 Node 的接口,该接口定义了节点的属性 value 和 next,它表示节点的值和指向下一个节点的指针。然后,我们定义了一个名为 LinkedList 的类,该类实现了链表的功能。add 方法来在链表中添加元素,具体操作如下:首先,将节点结构体作为参数传入方法,并根据链表是否为空来决定是否将其设置为头节点;否则,从头节点开始遍历链表,找到最后一个节点,将其下一个节点的引用指向该节点;然后将当前节点设置为该下一个节点的引用。remove 方法来从链表中删除元素,具体操作如下:首先,检查链表是否为空;然后,检查要删除的元素是否为头节点;如果是,直接将头节点指针指向下一个节点;否则,从头节点开始遍历链表,找到要删除的节点,将其前一个节点的引用指向该节点。

interface Node {  
  value: number;  
  next: Node | null;  
}  
  
class LinkedList<T> {  
  head: Node | null;  
  constructor() {  
    this.head = null;  
  }  
  
  add(value: number): void {  
    const node = { value, next: null };  
    if (!this.head) {  
      this.head = node;  
    } else {  
      const curr = this.head;  
      while (curr.next !== null) {  
        curr = curr.next;  
      }  
      curr.next = node;  
    }  
  }  
  
  remove(value: number): void {  
    if (!this.head) {  
      return;  
    }  
    if (this.head.value === value) {  
      this.head = this.head.next;  
      return;  
    }  
    const prev = this.head;  
    while (prev.next !== null && prev.next.value !== value) {  
      prev = prev.next;  
    }  
    if (prev.next !== null) {  
      prev.next = prev.next.next;  
    }  
  }  
  
  size(): number {  
    if (!this.head) {  
      return 0;  
    }  
    const curr = this.head.next;  
    while (curr !== null) {  
      curr = curr.next;  
    }  
    return curr.value + 1;  
  }  
}