算法(前端)

177 阅读3分钟

入门

数组中的最大值

export class Solution {
  /**
   * @param A: An integer
   * @return: a float number
   */
  maxOfArray(A) {
    // write your code here
    return Math.max(...A)
  }
}

生成给定大小的数组 4 生成 [1,2,3,4]

export class Solution {

  /**
   * generate
   *
   * @param size: An integer
   * @return: An integer list
   * 第一种
   */
  generate(size) {
    // write your code here
    return Array.from(new Array(size).fill(1), (item, index) => item = index +1)
  }
  // for循环
  generate(size) {
    // write your code here
    let arr = [];
    for(i=0;i<size;i++){
        arr.push(1+i);
    }
    return arr
  }
}

数组去重

    export class Solution {
      /**
       * @param arr: An arr
       * @return: a new arr
       */
      unique(arr) {
        // write your code here
        return Array.from(new Set(arr));
      }
}

链表转数组 输入 1->3->5->null 返回[1,3,5]

    export class Solution {
      /**
       * @param arr: An list
       * @return: a new arr
       */
      toArrayList(head) {
        // write your code here
        let s = []
        while(head){
            s.push(head.val)
            head = head.next
        }

        return s
  }
}

简单计算器

    export class Solution {
      /**
       * @param a: An integer
       * @param op: A character, +, -, *, /.
       * @param b: An integer
       * @return: The result
       */
      calculate(a, op, b) {
        // write your code here
        switch(op) {
            case "+":
              return a + b;
            case "-":
              return a - b;
            case "*":
              return a * b;
            case "/":
              return Math.floor(a / b);
            default:
              return 0;
        }
}

链表节点计数

输入:  1->3->5->null
	输出: 3
	
	样例解释: 
	返回链表中结点个数,也就是链表的长度.
        export class Solution {
      /**
   * @param head: the first node of linked list.
   * @return: An integer
   */
  countNodes(head) {
    // write your code here
    let num = 0;
    while(head){
      num++;
      head = head.next;
    }
    return num;
  }

反转一个三位整数

number = 123
321

number = 900
9

reverseInteger(number) {
    // write your code here
    let str = number + '';
    let arr = [...str].reverse();
    let newArr = [];
    for(let i=0;i<arr.length;i++){
      if(arr[i]===0) continue;
      newArr.push(arr[i])
    }
    let newStr = newArr.join('');
    let reversedNumber = +newStr;
    return reversedNumber;
  }

判断数字与字母字符

给出一个字符`c`,如果它是一个数字或字母,返回`true`,否则返回`false`
/**
   * @param c: A character.
   * @return: The character is alphanumeric or not.
   */
  isAlphanumeric(c) {
    // write your code here
    return /[A-Za-z0-9]/.test(c)

字符串查找

    对于一个给定的 `source` 字符串和一个 `target` 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从`0`开始)。如果不存在,则返回 `-1`
    /**
   * @param source: 
   * @param target: 
   * @return: return the index
   */
  strStr(source, target) {
    // Write your code here
    return source.includes(target) ? 1 : -1;
  }

数组中出现次数最多的值

    输入: 
    [1,1,2,3,3,3,4,5]
    输出: 
    3
  /**
   * @param array: An array.
   * @return: An interger.
   */
  findNumber(array) {
    // Write your code here.
    // 先使用reduce将数组变为对象
    const obj = array.reduce((add,item)=>{
            if(add[item]){
                add[item]++
            }else {
               add[item] = 1
            }
            return add
        },{})
        console.log(obj)
    const values = Object.values(obj);
    const keys = Object.keys(obj); 
    const maxNum = Math.max(...values);
    let num = keys.find(item=>{
            return obj[item+''] === maxNum
        })
    return Number(num)
  }

简单

字符删除

输入:  
str="They are students",sub="aeiou"
输出: 
"Thy r stdnts"

/**
   * @param str: The first string given
   * @param sub: The given second string
   * @return: Returns the deleted string
   */
  characterDeletion(str, sub) {
    // write your code here
    return str.replace(new RegExp(`[${sub}]`,'g'),'')
  }

翻转字符串

输入:"hello world"
输出:"dlrow olleh"

  /**
   * @param s: a string
   * @return: return a string
   */
  reverseString(s) {
    // write your code here
    let arr = [...s].reverse();
    return arr.join('')
  }

字符串中的单词数

输入: "Hello, my name is John"
输出: 5
解释:有五个字符串段落:"Hello""my""name""is""John"
/**
   * @param s: a string
   * @return: the number of segments in a string
   */
  countSegments(s) {
    // write yout code here
    let segmentCount = 0;

        for (let i = 0; i < s.length; i++) {
            if ((i == 0 || s.charAt(i - 1) == ' ') && s.charAt(i) != ' ') {
                segmentCount++;
            }
        }

        return segmentCount;
  }

翻转字符串

s = "the sky is blue"
"blue is sky the"

reverseWords(s) {
    // write your code here
   /**
   * @param s: A string
   * @return: A string
   */
   let newArr = []
    if(s == null || s.replace(/\s*/g,"") == " "){
      return ''
    }else {
      let strNum = s.trim().split(" ")
      for(var i= 0; i < strNum.length; i++){
        if(strNum[i] == ""){
          continue;
        }else {
          newArr.unshift(strNum[i])
        }
      }
    }
    return newArr.join(" ")
  }

反转字符串

输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"

/**
   * @param s: a string
   * @return: reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order
   */
  reverseWords(s) {
    // Write your code here
    const arr = s.split(' ');
    let arr1 = [];
    for(let i=0; i<arr.length; i++){
      arr1.push([...arr[i]].reverse().join(''))
    }
    return arr1.join(' ')
  }

首字母大写

输入: s =  "i jidls    mdijf  i  lsidj  i p l   "
输出: "I Jidls    Mdijf  I  Lsidj  I P L   "
/**
   * @param s: a string
   * @return: a string after capitalizes the first letter
   */
  capitalizesFirst(s) {
    // Write your code here
    let str = s.replace(/\b\w/g,(search,index,old) => {
        console.log(index,search,old)
        return search.toUpperCase()
    })
    return str
  }

只出现一次的字符

Example 1:
	Input: "abaccdeff"
	Output:  'b'
	
	Explanation:
	There is only one 'b' and it is the first one.


Example 2:
	Input: "aabccd"
	Output:  'b'
	
	Explanation:
	'b' is the first one.

/**
   * @param str: str: the given string
   * @return: char: the first unique character in a given string
   */
  firstUniqChar(str) {
    // Write your code here
    let arr = [...str]
    let obj = arr.reduce((allStrs,str1)=>{
      if(str1 in allStrs){
        allStrs[str1]++
      }else{
        allStrs[str1] = 1
      }
      return allStrs
    },{})
    const arr1 = Object.keys(obj);
    const out = arr1.find(item=>{
      return obj[item] === 1
    })
    return out
  }

最常见的单词

输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
输出:
"hit"
解释:
"hit"出现次数最多,为3次。

输入:
paragraph = "a a a b b b c c d"
输出:
"a"
解释:
"a""b" 出现次数都是3次,但是"a"的字典序最小。

//去除特殊字符~!@#$^-&*()=|{}':;',\[].<>/?~!@#¥……&*()——|{}【】';:""'。,、?

/**
   * @param paragraph: a string
   * @return: the most frequent word
   */
  mostCommonWord(paragraph) {
    // write your code here
    let str = paragraph.toLowerCase().replace(/[!?',;.]/g,"");
    const arr = str.split(" ");
    const obj = arr.reduce((allNames,item)=>{
      if(item in allNames){
        allNames[item]++
      }else{
        allNames[item] = 1
      }
      return allNames;
    },{})
    console.log(obj)
    let keys = Object.keys(obj);
    const flag = keys.every(item=>item.length===1)
    if(flag){
      keys.sort()
    }
    console.log(keys)
    const values = Object.values(obj);
    const max = Math.max(...values);
    const moreName = keys.find(item=>obj[item]===max)
    return moreName;
  }

数组第二大数

输入:[1,3,2,4]
输出:3
输入:[-1,-3,4,2]
输出:2
  /**
   * @param nums: An integer array
   * @return: The second max number in the array.
   */
  secondMax(nums) {
    // write your code here
    const arr = nums.sort((a,b)=>a-b);
    const index = arr.length-2
    const num = arr[index]
    return num
  }

寻找字母

给定一个字符串str,返回字符串中字母顺序最大的而且同时在字符串中出现大写和小写的字母。
如果不存在这样的字母,返回‘~‘。

输入:"aAbBcD"
输出:'B'
解释:因为c和D没有大小写同时出现,A和B都有大小写,但是B比A大,所以返回B。
/**
   * @param str: the str
   * @return: the letter
   */
  findLetter(str) {
    // Write your code here.
    let arr1 = [];
    for(let i=0;i<str.length;i++){  
	    if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
        //console.log(str.charAt(i));
		    let s = str.charAt(i).toLowerCase();
        //console.log(s);
		    if(str.includes(s)){
			    arr1.push(str.charAt(i));
		    }
	    }
     }
    // console.log(arr1);
    arr1 = arr1.sort().reverse();
    return !arr1[0] ? '~' : arr1[0]
  }

最后一个单词的长度

给定一个字符串, 包含大小写字母、空格 ' ',请返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

输入:"Hello World "
输出:5
/**
   * @param s: A string
   * @return: the length of last word
   */
  lengthOfLastWord(s) {
    // write your code here
    const arr = s.trim().split(' ')
    return arr[arr.length-1].length
  }

出勤判断

给定一个表示某学生出勤情况的字符串,‘A’代表出勤,‘D’代表缺勤,‘L’代表迟到。若该学生出现两次及以上缺勤或者连续三次及以上迟到则需要接受惩罚。请你判断该学生是否该接受惩罚并返回布尔类型。 输入样例1: “AADALLLAD”
输出样例1: true
样例解释1: 这名学生违约两次并且连续迟到三次,所以他应该受到惩罚

/**
   * @param record: Attendance record.
   * @return: If the student should be punished return true, else return false. 
   */
  judge(record) {
    // Write your code here.
    const arr = [];
    for(let i =0; i<record.length;i++){
        if(record.charAt(i)==='D'){
            arr.push('D');
        }
    }
    return arr.length >= 2 || record.includes('LLL');
  }

Excel表列标题

1 -> A
2 -> B
3 -> C
 ...
26 -> Z
27 -> AA
28 -> AB 
输入: 28
输出: "AB"
/**
   * @param n: a integer
   * @return: return a string
   */
  convertToTitle(n) {
    // write your code here
   let produce = "";
        getNext(n);
        return produce;

        function getNext(n) {
            let child = n%26;
            child = n%26 ==0 ? 26:child;
            produce = String.fromCharCode(child+64)+produce;

            if(n-child>0) {
                getNext((n-child)/26);
            }

        }
    }

删除多余的空格

输入: s = "The  sky   is blue"
输出: "The sky is blue"
/**
   * @param s: the original string
   * @return: the string without arbitrary spaces
   */
  removeExtra(s) {
    // write your code here
    var s= s.replace(/ +/g,' ')
    return s.trim()
  }

重复字符串匹配

输入 : A = "a"     B = "b".
输出 : -1

输入 : A = "abcd"     B = "cdabcdab".
输出 :3
解释:因为将A重复3次以后 (“abcdabcdabcd”), B将成为其的一个子串 ; 而如果A只重复两次 ("abcdabcd"),B并非其的一个子串.

/**
   * @param a: a string
   * @param b: a string
   * @return: return an integer
   */
  repeatedStringMatch(a, b) {
    // write your code here
   let tempS = a;
	     let count = 1;
		 while(a.length < b.length){
			 a+= tempS;
			 count++;
		 }
		 if(a.indexOf(b) >= 0) {
			 return count;
		 }
		 a=a+tempS;
		 if(a.indexOf(b) >= 0) {
			 return count+1;
		 }
		 return -1;
    }

最小移动次数

示例1:
输入:
S = "baaaaa"
输出: 1
解释:将字符串变成: "baabaa", 这样一次操作就可以使得字符串S没有三个相同的连续字母。

输入:
S = "baaabbaabbba"
输出: 2
解释:将字符串变成: "bbaabbaabbaa", 这样两次次操作就可以使得字符串S没有三个相同的连续字母。

输入:
S="baabab"
输出: 0
/**
   * @param s: a string
   * @return:  return the minimum number of moves
   */
  minimumMoves(S) {
    // write your code here
    let answer = 0, index = 0, eIndex = -1, letterCount = 0;
        while (index < S.length) {
            eIndex = index + 1;

            while (eIndex < S.length && S.charAt(index) == S.charAt(eIndex)) eIndex++;

            letterCount = eIndex - index;
            
            if (letterCount >= 3) {
                while (letterCount > 5) {
                    letterCount -= 3;
                    answer++;
                }
                
                if (letterCount <= 5) answer++;
            }
            index = eIndex;
        }
        return answer;
  }

中等