Skip to content

具有给定数值的最小字符串 #23

Description

@YalongYan

题目地址:具有给定数值的最小字符串

思路

因为是找最小字符串,所以先全部填充为a
然后从后面开始,往最大值z去设置,设置不了z,再设置其他最大的

代码

 // 先全部置为a 然后从后面开始 加z 
var getSmallestString = function(n, k) {
    let obj = {
        1: 'a',
        2: 'b',
        3: 'c',
        4: 'd',
        5: 'e',
        6: 'f',
        7: 'g',
        8: 'h',
        9: 'i',
        10: 'j',
        11: 'k',
        12: 'l',
        13: 'm',
        14: 'n',
        15: 'o',
        16: 'p',
        17: 'q',
        18: 'r',
        19: 's',
        20: 't',
        21: 'u',
        22: 'v',
        23: 'w',
        24: 'x',
        25: 'y',
        26: 'z',
    }
    let arr = new Array(n).fill('a')
    let sum = n
    let index = arr.length - 1
    if (n === k) return arr.join('')
    while (k - sum > 25) {
        arr[index] = 'z'
        index--
        sum += 25
    }
    let temp = k - sum + 1
    arr[index] = obj[temp]
    return arr.join('')
  };

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    算法New feature or request

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions