leetcode1663: The smallest string with a given value (1.26 a question per day)

Topic statement:

The numeric value of a lowercase character is its position in the alphabet (starting at 1), so a has numeric value 1, b has numeric value 2, c has numeric value 3, and so on.

A string is composed of several lowercase characters, and the value of the string is the sum of the values ​​of each character. For example, the numeric value of the string "abe" is equal to 1 + 2 + 5 = 8.

You are given two integers n and k. Returns the lexicographically smallest string of length equal to n and number equal to k.

Note that if the string x is located before y in the lexicographic order, it is considered that the lexicographical order of x is smaller than y, and there are two situations:

x is a prefix of y;
if i is the first position of x[i] != y[i], and x[i] comes before y[i] in the alphabet.
 

Example 1:

Input: n = 3, k = 27
Output: "aay"
Explanation: The value of the string is 1 + 1 + 25 = 27, which is the smallest lexicographical string whose value meets the requirements and whose length is equal to 3.
Example 2:

Input: n = 5, k = 73
Output: "aaszz"
 

hint:

1 <= n <= 1e5
n <= k <= 26 * n

Problem-solving ideas:

        The n given in the title is the length of the string, k is the sum of the values ​​corresponding to all characters, and the return value must be the string with the smallest lexicographical order that satisfies the condition.

        Traverse from 0 to n-1, calculate the length of the current subscript element to n, if the length x26 is greater than or equal to k, add "a" and k-1 to the string. When it is less than k, then use k to calculate the character corresponding to the current element, add the current character, and add the length 'z' to get the string that meets all the conditions.

In the addition of strings, s=s+st takes more time than s+=st. This question =+ will exceed the time limit.

Problem-solving code: 

class Solution {
public:
    string getSmallestString(int n, int k) {
        string s;
        for(int i=0;i<n-1;i++)
        {
            if((double)k/(n-1-i)>26.0)
            {
                string st(n-1-i,'z');
                char c='a'-1+(k-(n-1-i)*26);
                s+=c;
                s+=st;
                k=0;
                break;
            }
            else
            {
                k=k-1;
                s+="a";
            }
        }
            if(k)
            {
                char c='a'+k-1;
                s+=c;
            }
        return s;
    }
};

Guess you like

Origin blog.csdn.net/m0_63743577/article/details/128772556