likes
comments
collection
share

30 天刷题计划(一)

作者站长头像
站长
· 阅读数 32

26. 删除有序数组中的重复项

Code

function removeDuplicates(nums: number[]): number {

  if (!nums.length) {
      return 0
  }


 let slow = 0
 let fast = 0

  for (let i = 0; i < nums.length; i++) {
      if (nums[fast] !== nums[slow]) {
        slow++
        nums[slow] = nums[fast]
      }
      fast++
  }

 return slow + 1
};

1768. 交替合并字符串

思路

函数需要返回合并之后的字符串,所以先找到比较长的字符,挨个 push 字符,最后合并数组即可

Code

function mergeAlternately(word1: string, word2: string): string {
  let words = []
  let len = 0
  let max = Math.max(word1.length, word2.length)

  while(len < max) {
    if (word1[len]) {
      words.push(word1[len])
    }
    words.push(word2[len])
    len++
  }
   
  return words.join("")
};

1071. 字符串的最大公因子

Code

const gcd = (a, b) => b === 0 ? a : gcd(b, a % b)
const check = (x, str) => {
    let ans = ""

    while(ans.length < str.length) {
        ans += x
    }

    return ans === str
} 

function gcdOfStrings(str1: string, str2: string): string {
  let len1 = str1.length
  let len2 = str2.length
  let x = str1.substring(0, gcd(len1, len2))

  if(check(x, str1) && check(x, str2)) {
      return x
  }

 return ""
};
转载自:https://juejin.cn/post/7283776161528430629
评论
请登录